Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 641
waiwai933 Avatar asked Sep 11 '10 22:09

waiwai933


1 Answers

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?

like image 163
Guy Sirton Avatar answered Sep 28 '22 20:09

Guy Sirton