'What is the purpose of bit shifting? [closed]

I came across the below lines in code

unsigned char A = 0xB9;
unsigned char B = 0x91;
unsigned char C = A << 3; // shift bits in A three bits to the left.
unsigned char D = B >> 2; // shift bits in B two bits to the right.

I know that it's bit-shifting, but what purpose does it serve and when should one use it?



Solution 1:[1]

An example is a (monochrome) bitmap, where the pixels are represented by a single bit each. Suppose you have a circle

........
...oo...
..O..O..
.O....O.
.O....O.
..O..O..
...oo...
........

where a . is represented by a 0 bit and a O by an 1 bit, so the second line is represented by binary 00011000, or decimal 24. Now if you want to move the circle 1 pixel to the right, what you do is shift the bits in its representation 1 bit to the right.

........
....oo..
...O..O.
..O....O
..O....O
...O..O.
....oo..
........

So the second line is now 00001100 after shifting, (or decimal 12).

Solution 2:[2]

Bit shifting has several purposes

  • Multiplication or division by powers of two
  • Checking whether the most or least significant bit is set (MSB or LSB) is set by looking for overflow or underflow
  • Weak forms of encryption

Solution 3:[3]

Bit-shifting or Bit patterns are used for compressing files. Some use it for encryption too.

Solution 4:[4]

One use is division or multiplication by integer powers of 2.

Solution 5:[5]

There are a lot of uses for shifting. More than realistically can be explained here. A good example would be shifting values into the right position when assembling code. Also a left shift of 1 is the same as multiplying a value by 2, only much faster. Likewise a right shift is the same as dividing by 2.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 Peter Mortensen
Solution 3 craig1231
Solution 4
Solution 5 Peter Mortensen