bit twiddling (endianness)

Daniel Keep daniel.keep+lists at gmail.com
Mon Jan 8 06:49:51 PST 2007


Lutger wrote:
> Hi, I need to convert a uint to 4 ubytes in big endian order for which I 
> have written the function below. The thing is, I'm not 100% sure it is 
> correct for Big Endian systems, would somebody be so kind as to inform 
> me if this will work?
> 
> void concatUint(inout ubyte[] bytestream, uint num)
> {
>     bytestream.length = bytestream.length + 4;
>     static if (std.system.endian == Endian.LittleEndian)
>     {
>         bytestream[$-4] = num >> 24;
>         bytestream[$-3] = num >> 16;
>         bytestream[$-2] = num >> 8;
>         bytestream[$-1] = num;
>     }
>     else // big endian
>     {
>         bytestream[$-4] = num;
>         bytestream[$-3] = num >> 8;
>         bytestream[$-2] = num >> 16;
>         bytestream[$-1] = num >> 24;
>     }
> }

Taking, as an example, 0x0A0B0C0D: for little endian it should be stored 
as 0x0D0C0B0A, and for big endian it should be 0x0A0B0C0D.

0x0A0B0C0D >> 24 == 0x0A, so I *think* you've got them backwards.

http://en.wikipedia.org/wiki/Little_Endian#Big-endian

	-- Daniel


More information about the Digitalmars-d-learn mailing list