Are there any good reasons to use bit shifting except for quick math

bit-manipulationbit-shift

I understand bitwise operations and how they might be useful for different purposes, e.g. permissions. However, I don't seem to understand what use the bit shift operators are. I understand how they work, but I can't think of any scenarios where I might want to use them unless I want to do some really quick multiplication or division. Are there any other reasons to use bit-shifting?

Best Answer

There are many reasons, here are some:

  1. Let's say you represent a black and white image as a sequence of bits and you want to set a single pixel in this image generically. For example your byte offset may be x>>3 and your bit offset may be x & 0x7 and you can set that bit by: byte = byte | (1 << (x & 0x7));
  2. Implementing data compression algorithms where you deal with variable length bit sequences, e.g. huffman coding.
  3. You're are interacting with some hardware, e.g. a serial communication device, and you need to read or set some control bits.

For those and other reasons most processors have bit shift and/or rotation instructions as well as other logic instructions (and/or/xor/not).

Historically multiplication and division were significantly slower as they are more complex operations and some CPUs didn't have those at all.

Also see here: Have you ever had to use bit shifting in real projects?