> Is there any standard function to test the endianess of the system?
inline bool little_endian()
{
union
{
long i ;
char c[ sizeof(long) ] ;
};
i = 1 ;
return c[0] == 1 ;
}
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
> what about solving little/big endian problem by doing appropriate typecast before writing to file?
Because endian can't be fixed with a simple cast.
You have to write code to rearrange the bytes into the correct order.
> Is there any standard function to test the endianess of the system?
Not only is this non-portable (it assumes far too much about internal representations), it also assumes that there are only two endian systems (there's at least 3).
http://en.wikipedia.org/wiki/Endianness
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
If you know your target value will fit in a smaller integer, you really don't need to worry about endianness. Do as tesuji suggests and let the compiler do the appropriate movement:
fputc( unsignedlongvar, file ); // bits 8..31 are lost!
Don't usefwrite() for size-specific I/O. The C and C++ standards require a char to be one byte (eight bits), but there is no requirement on internal representation. So it is possible to find some funky system/compiler that stores them in word values... and if the endianness isn't strictly little-endian, then using fwrite() won't work.
Hope this helps.
Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
> Is there any standard function to test the endianess of the system?
This was an original question - what are you smoking?
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953