Wednesday, June 25, 2014

I don't understand the BITWISE Operators

Bitwise operators, shift left, shift right, bitwise OR, bitwise AND, etc, are typically used in association with the hardware.  Wikipedia has a very detail description of their functionalities.  I won't repeat it here.  Instead, I'll try to explain how it is used with an example.

Suppose we want to independently control three lights: red, green, yellow.  Computer can implement it with a few methods:

  • 6 distinct addresses and ignore data:  Ron, Roff, Gon, Goff, Yon, Yoff
  • 3 distinct addresses and use 1 to turn on, 0 to turn off.  Ex. Red(1) turns red on, Green(0) turns green off.
  • 1 address and use 3 bits data: each bit control different light.  If you do not know bits, please check wiki's binary number.  Ex. Light(101) turns R on, G off, Y on.
The single address case (the last one) is where we need to use bitwise logic.  Try this question:
  • How do you turn on Green and keep the other lights unchanged?
  • How do you turn off Green and keep the other lights unchanged?
Shift operations are usually used with math.  The number is divided by 2 if you shift right and multiplied by 2 if you shift left.  Of course, there are other usage too.

No comments:

Post a Comment