Re: Robust detection of endianness at compile time.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Andrew Haley <aph-gcc@xxxxxxxxxxxxxxxxxxx> wrote:
>
> It would work on gcc, because gcc allows members of a union to be
> written as one type and read as a different incompatible type.  Other
> C compilers allow this too.  However, it's is not guaranteed by the
> language standards, so it doesn't much help you with truly portable
> code.

Right.  It is also a bad idea to use 'register', as some compilers
incorrectly use it to change representation - or they used to.

The safest and most portable code involves setting a variable to
a known value, reading each byte of the variable as an unsigned
char, and using AI to deduce the endianness.

For integers in C99 or on any system with a fairly conventional
binary representation (don't ask), you can generate a translation
table directly by storing (say) (0<<24)+(1<<16)+(2<<8)+3 and using
the result as unsigned char [4].

Doing the same for IEEE 754 formats is left as an exercise for
the reader :-)  I have done it often enough, but it is tedious.

If you are faced with doing this for a system with integers that
don't match C99's model, or with floating-point that doesn't have
a base of 2 or 16, real numbers that are not floating-point or
anything similar, then please contact me by Email before I retire.
That isn't entirely a joke :-)


Regards,
Nick Maclaren,
University of Cambridge Computing Service,
New Museums Site, Pembroke Street, Cambridge CB2 3QH, England.
Email:  nmm1@xxxxxxxxx
Tel.:  +44 1223 334761    Fax:  +44 1223 334679

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux