Re: Endianess...

From: Howard (alicebt_at_hotmail.com)
Date: 02/03/05


Date: Thu, 03 Feb 2005 16:53:52 GMT


"Victor Bazarov" <v.Abazarov@comAcast.net> wrote in message
news:gsaMd.41110$NC6.2257@newsread1.mlpsca01.us.to.verio.net...
> Victor Bazarov wrote:
>> pellepluttrick@yahoo.com wrote:
>>
>>> [...]
>>> // Remember: stored in memory as 0x34 0x12
>>
>>
>> That means that 0x34 has *lower* address than 0x12.
>>
>>> unsigned short us = 0x1234;
>>>
>>> char buf[2];
>>>
>>> // Convert from little-endian to big endian
>>> buf[0] = us & 0xFF; // Should now contain 0x12
>>
>>
>> Why? (0x1234 & 0x00ff) gives 0x34.
>
> Wanted to add: "...regardless of endianness."
>
>>
>>> buf[1] = (us >> 8) & 0xFF; // Should now contain 0x34
>>
>>
>> Why? (0x1234 >> 8) gives 0x12.
>
> regardless of endianness, again.
>
>> [...]

Hi Pelle

    Just in case it wasn't clear to you what Victor was saying: when you
shift bits like that, you don't have to worry about what the order of bytes
in the physical memory is. Just treat it like you would on paper. Shifting
to the right, for example, will shift the high-order bits towards the
low-order side, and it does not matter whether the low-order byte is stored
in a higher or lower location in physical memory. So, using your example,
doing 0x1234 >> 8 will always result in 0x0012, and never in 0x3400,
reagardless of the machine's byte ordering.

    You only really need to worry about byte ordering when reading values
from a data stream on a machine that has one ordering when that data was
written using the opposite ordering.

    (What our software does is use a compile flag that, when compiling for
the PC, byte ordering is intentionally reversed when reading or writing, so
that we know it will match what's done on the Mac. When compiled on the
Mac, reading and writing is done without changing the ordering. We use
#defines and #ifdefs to determine whether to call the order-reversing code
or not.)

-Howard



Relevant Pages