Bit-Shift operators are big-endian

First, let’s have a look at how we can represent actual bits.

Some people represent little endian unsigned 32bit ints as 4 bytes, each of which is aligned in big-endian order:

[25,26,27,28,29,30,31,32][17,18,19,20,21,22,23,24][9,10,11,12,13,14,15,16][1,2,3,4,5,6,7,8]

I don’t like this!

Instead, let’s represent individual bits, and ignore the bytes.
Here 32 is the least significant bit, and 1 is the most significant.

So little-endian is represented as:

[32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]

This means a value of 2 will be stored in memory as

01000000000000000000000000000000

Big endian is represented as:

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32]

This means a value of 2 will be stored in memory as

00000000000000000000000000000010

Now, on a little-endian system, let’s have a look at what happens when we perform right shift:

unsigned int K = 78498;
unsigned int K_shifted = K >> 1;

std::bitset<32> val1 = K;
std::cout << "\n normal  bits = ";
for (auto i = 0; i < 32; ++i)
{ std::cout << val1[i]; }


std::bitset<32> val1_shifted = K_shifted;
std::cout << "\n shifted bits = ";	
for (auto i = 0; i < 32; ++i)
{ std::cout << val1_shifted[i]; }

Output:

normal  bits = 01000101010011001000000000000000				
shifted bits = 10001010100110010000000000000000

As you can see, performing the right shift actually moved the bits to the left.
Thus, it’s worth remembering that bit-shift operations are designed to make sense on big-endian systems.

Why is it important to know this?

In most cases you will work with whole values, so if you just “pretend” you are working with big-endian memory, the operations will make sense.
However, let’s say you want to take the second byte out of an unsigned int in this violent way by directly accessing bytes in memory:

unsigned int K = 123456
unsigned char* pY = reinterpret_cast<unsigned char*>(&K); 
K >> 1;
pY++;
auto result = *pY;

If you aren’t aware how the bit shifting happens, you might get an unexpected result!

Leave a Reply

Your email address will not be published. Required fields are marked *