Packing/unpacking binary data in C - doubles, 64 bits

Kevin D. Clark kevin_d_clark at comcast.net
Wed Sep 9 14:57:05 EDT 2009


1:  If I were you, I would start using datatypes like uint64_t and
int32_t in your protocol code.

2:  Typically, binary stuff is sent over the network in "network byte
order" and network byte order is big-endian.  This statement is not
universally agreed to -- in fact I used to work at a shop where they'd
never even considered this problem and it turned out that they were
sending (most) stuff over the wire in little-endian format.

3:  Here's some sample code that unpacks a 64-bit integer in network
byte order:

 unsigned char raw[8];  /* these are the raw bytes 
                           you got from the wire */
 uint64_t u64result;

 u64result = (((uint64_t)raw[0]) << 56) |
             (((uint64_t)raw[1]) << 48) |
             (((uint64_t)raw[2]) << 40) |
             (((uint64_t)raw[3]) << 32) |
             (((uint64_t)raw[4]) << 24) |
             (((uint64_t)raw[5]) << 16) |
             (((uint64_t)raw[6]) << 8) |
             (((uint64_t)raw[7]));

4:  Sending binary doubles over the wire can be very complicated.

5:  If at all possible, consider encoding your protocol in ASCII text
rather than sending binary stuff on the wire.

Kind regards,

--kevin
-- 
GnuPG ID: B280F24E                God, I loved that Pontiac.
alumni.unh.edu!kdc                -- Tom Waits
http://kdc-blog.blogspot.com/     


More information about the gnhlug-discuss mailing list