Ann said:
I am opening a file which looks like 0xABCDEF01 on another machine but
0x01EFCDAB on my machine.
Is this a byte swapping?
Looks like it.
Could anyone give a good way to check if bytes are being swapped? (code
should work smoothly across different machine.)
In principle, there is no reliable way to tell. If you read a 32-bit
unsigned integer from a file and get a value of 0xABCDEF01, how can
you know whether it should be 0xABCDEF01 or 0x01EFCDAB? Without more
information, you can't. Even with more information, you may not be
able to tell.
If you're storing binary data in a file, byte ordering is only one of
the problems you can run into. Sizes of types can vary across
different implementations; so cah floating-point representations.
The safest approach is to write *only* byte data. For example, if you
want to write an integer value 0x01EFCDAB to a file, you can read and
write the individual bytes (0x01, 0xEF, 0xCD, 0xAB) in a fixed order.
Or you can write a textual representation of the number, which also
has the advantage of letting you view the file with a text editor.
Strictly speaking, you might still have problems on systems with byte
sizes bigger than 8 bits, or with non-ASCII character sets; the former
is unlikely to arise in practice, and the latter can be solved with
textual conversion tools. (There are systems, mostly DSPs, with bytes
bigger than 8 bits, but they're embedded systems, and you're not
likely to need to share files with them.)
If you must write raw binary data to a file, you might add information
to the file header indicating how the data is formatted.