Re: platform independent bit shifting



"Willem" <willem@xxxxxxxx> wrote in message
news:slrnep7p32.2k5s.willem@xxxxxxxxxxxxxxxxxx
Andrew wrote:
) i'm trying to make sure my program runs on different platforms but don't
) have access to a big-endian system for testing.
)

By the way, the safest way to make your program endianess-independent is
to make sure that all operations that input and output bytes (to files or
to the network or whatever) work byte by byte.

To add some detail to this, consider saving a 4-byte value (e.g. an 'int')
to a file in an endian-independent manner. You can either save it
most-significant-byte first or least-significant-byte first and this defines
the endianness of the data /in the file/. The endianness of the processor
is unimportant.

So:

saveint(int32 i)
{
savebyte(i >> 24); /* msb first */
savebyte(i >> 16);
savebyte(i >> 8)
savebyte(i);
}

int32 restoreint()
{
int32 a;
a = restorebyte(); /* msb first */
a <<= 8; a += restorebyte();
a <<= 8; a += restorebyte();
a <<= 8; a += restorebyte();
}

--
Roger


.


Quantcast