Search code examples
cendianness

Does bit-shift depend on endianness?


Suppose I have the number 'numb'=1025 [00000000 00000000 00000100 00000001] represented:

On Little-Endian Machine:

00000001 00000100 00000000 00000000

On Big-Endian Machine:

00000000 00000000 00000100 00000001

Now, if I apply Left Shift on 10 bits (i.e.: numb <<= 10), I should have:

[A] On Little-Endian Machine:

As I noticed in GDB, Little Endian does the Left Shift in 3 steps: [I have shown '3' Steps to better understand the processing only]

  1. Treat the no. in Big-Endian Convention:

    00000000        00000000        00000100    00000001
    
  2. Apply Left-Shift:

    00000000        00010000        00000100        00000000
    
  3. Represent the Result again in Little-Endian:

    00000000        00000100        00010000        00000000 
    

[B]. On Big-Endian Machine:

00000000        00010000        00000100        00000000

My Question is:

If I directly apply a Left Shift on the Little Endian Convention, it should give:

numb:

00000001 00000100 00000000 00000000

numb << 10:

00010000 00000000 00000000 00000000

But actually, it gives:

00000000        00000100        00010000        00000000 

To achieve the second result only, I have shown three hypothetical steps above.

Please explain me why the above two results are different: The actual outcome of numb << 10 is different than the expected outcome.


Solution

  • Endianness is the way values are stored in memory. When loaded into the processor, regardless of endianness, the bit shift instruction is operating on the value in the processor's register. Therefore, loading from memory to processor is the equivalent of converting to big endian, the shifting operation comes next and then the new value is stored back in memory, which is where the little endian byte order comes into effect again.

    Update, thanks to @jww: On PowerPC the vector shifts and rotates are endian sensitive. You can have a value in a vector register and a shift will produce different results on little-endian and big-endian.