Gianni Mariani wrote:
>
> An alternative is to allways write the file in the same endianness.
Good idea.
>
> That way you can determine at compile time, which endianness to use.
Or you could write code that is independent of endianness. Writing code
to handle every possible byte order seems excessive, problematic, and
unnecessary.
> I have written a class (NetworkOrder) and posted a couple of times. It's
> available from google:
>
> http://groups.google.com/groups?hl=e...4%40mariani.ws
>
>
> This fancy method determines the endianness of the machine. With full
> optimization on, it's code is elminated and is equivalent to a constant.
>
> static inline bool IsBigEndianbool()
> {
> const unsigned x = 1;
> return ! ( * ( const char * )( & x ) );
> }
But... this tells you very little, really. In fact, it can return true
for something that is NOT big-endian.
I just think that this is a fundamentally bad way of doing file I/O. I
would use something like this instead:
int BytesToInt(unsigned char bytes[])
{
int result = 0;
for (int i=0; i<sizeof(int); ++i)
{
result = (result << CHAR_BIT) | bytes[i];
}
}
Of course this could be made much more general and safe with a few
modifications. For example: it could be made a template to handle
different types, it could use a vector instead of an array to pass the
bytes in, it could indicate a number of bytes to convert and throw an
exception if the number of bytes to convert exceeds the number of bytes
in the destination type, etc.
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.