Gernot Frisch wrote:
<snip>
How about:
struct
{
long a;
long b;
}s;
fread(&s, sizeof(s), file); ??
That'll indeed read each long according to the platform byte-order. See
below.
- Type casts to access parts of variables,
unsigned long a = 0xFFFF0000;
unsigned char b = (unsigned char) a;
Does this cause a problem?
No. Casts between integer types always work from the little end,
regardless of byte order.
<snip>- Bit operations; for example for graphics.
long a = 0xffff;
long b = a& 0xff ??
No problem there. Hexadecimal literals are specified in standard
hexadecimal notation.
How do developers handle these problems?
-Gernot
The only problem you've addressed is reading data from a binary file.
Assuming that you want to be able to share data files between platforms,
you need to decide on a byte order as part of the file format. Then use
some functions to convert endianness as needed.
Here's a bit of some code I used for this:
----------
union ByteOrderer {
char b[4];
short s;
long l;
};
short LEShort(short s) {
union ByteOrderer le;
le.b[0] = (char) (s & 0xFF);
le.b[1] = (char) ((s & 0xFF00) >> 8);
return le.s;
}
----------
LEShort converts a short from little-endian to native BO or vice versa.
It's trivial to write LELong, BEShort and BELong on the same basis.
Of course, chances are you won't need both LE and BE functions in the
same program, unless you're reading/writing a variety of formats that
use different orders.
The other kind of problem you're likely to encounter is if you try to
access the same contents of memory as different types, either by casting
a pointer or using a union. (OK, so my snippet does this, but that's
because the whole point is to convert endianness.) If you want
portability here, you'll probably need to rewrite the code e.g. to use
shifts instead.
Stewart.
--
My e-mail is valid but not my primary mailbox, aside from its being the
unfortunate victim of intensive mail-bombing at the moment. Please keep
replies on the 'group where everyone may benefit.