Sunday, May 19, 2013

Bit Shiting

if you look at the binary representations of the following numbers you may notice something peculiar:
0001 = 1
0010 = 2
0100 = 4
1000 = 8
Each time we shift the number one space to the left, the value of the number doubles. This doesn't only work for one bit, take a look at this more complicated example.
0001 0101 = 21
0010 1010 = 42
Again, one shift to the left and the number has doubled. On the other hand, one shift to the right halves the value.
Computers are notoriously bad at doing multiplication and division, it takes lots of CPU time and can really slow your code down. To try and get past this problem computers can shift the values in registers and as long as multiplication or division is by powers of 2, then the CPU time is reduced as the action takes only one line of Machine Code. There are several types of shifts that processors can perform:
  • Logical Shift
Shifting either left or right, you add a 0 on the empty end.
  • Arithmetic Shift
You maintain the sign bit of the number being shifted.
Rotate right arithmetically.svg
Please note the Logical shift example is also an example of an arithmetic shift as the sign remains the same. You'll find out about sign bits when learning about two's complement
  • Circular Shift
The bit that is pushed off one end appears on the other

No comments:

Post a Comment