home bbs files messages ]

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,616 of 33,346   
   James K. Lowden to fmatthew5876@googlemail.com   
   Re: Strict aliasing and marshalling   
   25 Oct 12 19:02:26   
   
   From: jklowden@speakeasy.net   
      
   On Thu, 25 Oct 2012 14:06:44 -0700 (PDT)   
   fmatthew5876  wrote:   
      
   > 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;   
   > }   
      
   Can you?  I've heard that called type-punning.  Section 9.5 of the   
   standard says, "the value of at most one of the non-static data members   
   can be stored in a union at any time."  IOW, you can only read what you   
   wrote; you can't assume u32 and u8 are at the same address.   
      
   Me, I would call htonl or similar.  I haven't seen a serialization   
   library I like yet.   
      
   --jkl   
      
      
   --   
         [ 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