<< relearned <<|

Bit shifting, done by the << and >> operators, allows in C languages to express memory and storage access, which is quite important to read and write exchangeable data. But:

Question: where is the bit when moved shifted left?

Answere: it depends

Long Answere:

// On LSB/intel a left shift makes the bit moving 
// to the opposite, the right. Omg 
// The shift(<<,>>) operators follow the MSB scheme
// with the highest value left. 
// shift math expresses our written order.
// 10 is more than 01
// x left shift by n == x << n == x * pow(2,n)
#include <stdio.h> // printf
#include <stdint.h> // uint16_t

int main(int argc, char **argv)
  uint16_t u16, i, n;
  uint8_t * u8p = (uint8_t*) &u16; // uint16_t as 2 bytes
  // iterate over all bit positions
  for(n = 0; n < 16; ++n)
    // left shift operation
    u16 = 0x01 << n;
    // show the mathematical result
    printf("0x01 << %u:\t%d\n", n, u16);
    // show the bit position
    for(i = 0; i < 16; ++i) printf( "%u", u16 >> i & 0x01);
    // show the bit location in the actual byte
    for(i = 0; i < 2; ++i)
        printf(" byte[%d]", i); 
  return 0;

Result on a LSB/intel machine:

0x01 << 0:      1 
1000000000000000 byte[0] 
0x01 << 1:      2 
0100000000000000 byte[0] 
0x01 << 2:      4 
0010000000000000 byte[0] 
0x01 << 3:      8 
0001000000000000 byte[0]

<< MSB Moves bits to the left, while << LSB is a Lie and moves to the right. For directional shifts I would like to use a separate operator, e.g. <<| and |>>.

One thought on “<< relearned <<|

  1. I submit that the left-to-right behavior your code demonstrates is not machine-dependent. Rather, it is an artifact of your 16-position printf loop. Arithmetically, the iteration will always show the LSb first and MSb last. If you want the most significant bit on the left, you need reverse the loop. However, since this all happens within the ALU (rather than memory), you’ll see consistent behavior across big-endian and little-endian machines (which is the abstraction that shift instructions preserve for us).

    A big-endian machine such as SPARC or HP 9000 will demonstrate nearly the same output. The byte-indexes will be swapped, which is the genuine problem in porting bit-twiddling algorithms between machines.

Comments are closed.