Packing/unpacking binary data in C - doubles, 64 bits
Bruce Labitt
bruce.labitt at myfairpoint.net
Wed Sep 9 21:40:21 EDT 2009
Kevin D. Clark wrote:
> 1: If I were you, I would start using datatypes like uint64_t and
> int32_t in your protocol code.
>
>
I'll try to do that.
> 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.
>
>
That only works if both ends are the same - definitely not portable. In
my case, the client is little-endian and the server is big-endian.
> 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]));
>
>
Thanks for the sample code! How about packing? What do you do about sign?
> 4: Sending binary doubles over the wire can be very complicated.
>
>
Why? Encode to a standard. IEEE-754 would be logical. Is that
complicated? What am I missing? In my OP, the url I provided has
functions that pack and unpack IEEE754 floats and doubles. I never
looked at the floats, but the double stuff works.
> 5: If at all possible, consider encoding your protocol in ASCII text
> rather than sending binary stuff on the wire.
>
Again, why? Sure it is easier to debug. When I am just trying stuff
out, I use text. For performance, I always end up using binary.
> Kind regards,
>
> --kevin
>
I always learn something from these discussions.
Thanks Again,
Bruce
More information about the gnhlug-discuss
mailing list