[LCP]#defines to know Endianness
Paul Gearon
gearon at ieee.org
Fri Jul 2 21:16:02 UTC 2004
Greg Black wrote:
> You have two choices:
>
> 1. Find something like I suggested that works on all the
> platforms you care about; or
>
> 2. Write your own macro and use that -- it's incredibly
> trivial, after all.
>
> You might also ask yourself why you're doing this at all. It's
> rare for well-written code to need to know stuff like this.
I agree here. It's normally only necessary for making data compatible
across machines of different architectures. This includes saved files
and network communications.
If it's network communications that you're considering, then it's
possible that you're operating at too low a level. I'd recommend
considering your options for using a higher level protocol.
Otherwise, the fact that networking needs this stuff provides a hint.
You can use htonl and ntohl, which were both designed for this purpose.
They convert data into a common "network" format. This can be useful
for file use as well.
The nice thing about these functions is that they are normally
implemented as macros. On big endian platforms they do nothing (so the
pre-compiler gets rid of it. For non-macro implementations the
optimizer can get rid of it), and on x86 (the predominant little endian
platform) the macro is normally implemented with a bswap assembly
instruction, which has less overhead than any macro you'd come up with.
In fact, have a look at netinet/in.h on Linux and you'll see that it
does just this. These functions/macros are available on all other
platforms including Windows.
--
Regards,
Paul Gearon
Software Engineer Telephone: +61 7 3876 2188
Tucana Technologies Fax: +61 7 3876 4899
http://www.tucanatech.com
Catapultam habeo. Nisi pecuniam omnem mihi dabis, ad caput tuum saxum
immane mittam.
(Translation from latin: "I have a catapult. Give me all the money,
or I will fling an enormous rock at your head.")
More information about the linuxCprogramming
mailing list