Forums before death by AOL, social media and spammers... "We can't have nice things"
|    comp.lang.c++.moderated    |    Moderated discussion of C++ superhackery    |    33,346 messages    |
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
|    Message 32,614 of 33,346    |
|    fmatthew5876 to All    |
|    Re: Strict aliasing and marshalling    |
|    25 Oct 12 14:06:44    |
   
   From: fmatthew5876@googlemail.com   
      
   >The C++ standard requires that memory returned by new is at least   
   >aligned to sizeof(void*). As far as I know GCC aligns memory to   
   >sizeof(void*) * 2 (= 8 for 32-bit, = 16 for 64-bit), so you won't   
   >get an unaligned read here.   
      
   This is assuming buffer is a pointer to an array of characters anywhere   
   in memory. It could actually be in the middle of binary buffer allocated   
   by new or created on the stack. Therefore we can't make any assumptions   
   about its alignment.   
      
   > Lots of comments about endianness   
      
   I know about endian, thats another issue and easy enough to deal with.   
   You can call be32/le32_to_cpu() on the integer after pulling it out of   
   the buffer.   
      
   The real question is the safest and most efficient way to unpack an   
   unaligned buffer into an aligned binary object such as a 32 bit integer.   
      
   Why waste time with bit shifts and ors? You could do something like this:   
      
   //assume the data is big endian   
   inline uint32_t unpackbe32(unsigned char* buf) {   
    union {uint32_t u32; uint8_t u8[4] } u;   
   #if LITTLE_ENDIAN   
    u.u8[3] = buf[0];   
    u.u8[2] = buf[1];   
    u.u8[1] = buf[2];   
    u.u8[0] = buf[3];   
   #else   
    u.u8[0] = buf[0];   
    u.u8[1] = buf[1];   
    u.u8[2] = buf[2];   
    u.u8[3] = buf[3];   
   #endif   
    return u.u32;   
   }   
      
      
   --   
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
(c) 1994, bbs@darkrealms.ca