Search code examples
c++32-bitbit-shift

Unsigned integer into little endian form


Possible Duplicate:
convert big endian to little endian in C [without using provided func]

I'm having trouble with this one part: If I wanted to take a 32 bit number, and I want to shift its bytes (1 byte = 8 bits) from big endian to little endian form. For example:

Lets say I have the number 1.

In 32 bits this is what it would look like:

1st byte 2nd byte 3rd byte 4th byte
00000000 00000000 00000000 00000001

I want it so that it looks like this:

4th byte 3rd byte 2nd byte 1st byte 
00000001 00000000 00000000 00000000 

so that the byte with the least significant value appears first. I was thinking you can use a for loop, but I'm not exactly sure on how to shift bits/bytes in C++. For example if a user entered in 1 and I had to shift it's bits like the above example, I'm not sure how I would convert 1 into bits, then shift. Could anyone point me in the right direction? Thanks!


Solution

  • << and >> is the bitwise shift operators in C and most other C style languages.

    One way to do what you want is:

    int value = 1;
    uint x = (uint)value;
    int valueShifted = 
        ( x << 24) |                // Move 4th byte to 1st
        ((x << 8) & 0x00ff0000) |  // Move 2nd byte to 3rd
        ((x >> 8) & 0x0000ff00) |  // Move 3rd byte to 2nd
        ( x >> 24);                 // Move 4th byte to 1st