Don't use bit fields, and in general, don't rely on any bit/byte layout. If
you have a short, int or long, use them as whole, don't access them
partially through pointers to chars. Rather, extract the appropriate bit
from its bit position by means of a bit mask, e.g. to set a bit in an int at
position n:
myint |= 1<<n;
to reset it:
myint &= ~(1<<n);
to check it:
if (myint & (1<<n)) op1(); // if bit's set
else op2(); // if bit's clear
And don't save any nontext data (anything other than array of characters) to
a file using fwrite(), likewise don't read with fread() anything other than
characters from a file. And you should be OK and free from the endianness.
You may develop functions to decompose short, int and long into a series of
chars using the methods similar to the above, something like this:
int i;
FILE *f = ...;
unsigned x = ...;
for (i=0; i<sizeof(x); i++)
{
unsigned char c = x & UCHAR_MAX;
fwrite (&c, 1, 1, f);
x >>= CHAR_BIT;
}
the above will save the entire integer x in LSB first way regardless of the
CPU's endianness.
It's a good question whether or not I should use 8 instead of CHAR_BIT... I
know some odd system (a DSP) where char is 16-bit long, there, I believe,
the bits 8 through 15 are ignored when char is saved. Actually, no, they
shouldn't be ignored, but then again, the file is still a sequence of 8-bit
chars (the DSP saves files to the PC through JTAG). I'm not sure of this
particular thing as I usually saved raw data in 16-bit pieces (shorts), not
any kind of text...
HTH,
Alex
Hi,
Such as I have following bitmap structure and assigned value:
struct bm
{
char high2bits:2;
char mid4bits:4;
char low2bits:2;
};
bm.high2bits = 3;
bm.mid4bits = 0;
bm.low2bits = 0;
The char value is 0x03 in little endian mode, and the char value is 0xc0 in
big endian mode. How to eliminate the bitmap difference?
Thanks,
Eric