In C

a << b Shifts all bits in a the left by b amount of bits, filling the rest with zero a >> b shifts all the bits in a to the right by b bits.

Performing bitwise operations on two values of different sizes will perform integer promotion, promoting the smallest size type.

Signed Extensions

Shifting a signed value to the right would fill the leftmost created values with the appropriate sign. I.e, shifting a signed in that start with a 1 by 4 bits would create four bits with a one on the left and truncate the bottom four. If the first bit is a 0, then they are filled with zeroes.

Destructive Bitshifts

Bitshifts are effectively always destructive. If you bitshift a signed value to the left and its first bit happened to be a one, you can make a negative value from a positive one even if the intended operation was to multiple by two by bitshifting to the left.

Specific Operations

&

  • And-ing a value with a any all-ones value like FF always results in a copy.
  • And-ing a value with any all0zero values like 00 will always result in 0.
  • And-ing a value with itself will result in itself.

|

  • Or-ing with a value that’s all zero will copy the value as well.

>>

  • Bitshifting a value to the right by n bits is effectively the same as integer division by 2^n. For example:
int a = 8;  
int b = 13;  
a = a >> 1;  
b = b >> 2;  
assert(a == 4);//true  
assert(b == 3); //true

<<

Bitshifting to the left is exactly the opposite, multiplying by 2^n. For example:

int a = 3;
a = a << 3;
assert(a == 24);

If attempting to perform a bitwise operation with a type mismatch, the smaller type will be promoted (extended) to match types.

^

Xor operator. Will result in a 1 if the two operands are of different values.

~

Not operator. Flips the bit.