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)
if(u8p[i])
printf(" byte[%d]", i);
printf("\n");
}
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 |>>.