Packing/unpacking binary data in C - doubles, 64 bits
Ben Scott
dragonhawk at gmail.com
Tue Sep 8 21:42:19 EDT 2009
On Tue, Sep 8, 2009 at 8:16 PM, Bruce
Labitt<bruce.labitt at myfairpoint.net> wrote:
> The server is a big-endian machine and the client a
> little-endian machine, so one can't just sleaze out and
> directly send binary data on the network.
...
> to send and receive 32 bit integers, 16 bit integers, and doubles. It
> would be very nice, but not required to be able to transfer 64 bit integers.
The C/POSIX native answer to this is a family of functions which
convert integers from "host" to "network" order, and vice versa.
"Host" is whatever your machine uses natively. "Network" is the order
used by Internet Protocol. If they are the same, the functions are
no-op's. Otherwise, they do the needed conversions.
The integer conversion functions are htons(3) and htonl(3) (host to
network, short/long), and their inverses, ntohs(3) and ntohl(3)
(network to host, short/long). All unsigned (I guess signed integers
don't exist on the Internet).
I believe these functions follow 32-bit platform conventions even on
64-bit machines -- so with these four functions, a short int is 16
bits and a long int is 32 bits. The intertubes suggest htonll() and
ntohll() may exist on 64-bit platforms.
Whether or not any of the above is "the right solution" for you is
open to debate. :-)
I haven't touched floating point at the C/machine level in forever
(possibly not since college). I got nothing for that.
-- Ben
More information about the gnhlug-discuss
mailing list