# 52: Bits Operations: Shifting.

by Wahid Tanner | Feb 9, 2016 |

You can do more with bits than just turning them on or off. This episode will show you how to shift bits left or right for either really quick multiplication or division or to maneuver them into place.

If you start out with the value 0x5a and want to first isolate the 5 digit, the previous episode explains how to use masking to accomplish this. After masking, you have 0x50 which is not quite the value 5 that you might need. If you want to convert 0x50 into 0x05, then you’re going to have to shift it to the right.

Shifting either left or right is based on binary digits not hexadecimal digits. Because each hexadecimal digit is composed of four binary digits, then to shift a hexadecimal value by one of its own digits, you’ll need to shift the underlying bits by four positions.

Let me show you this in binary with the value 0x50:

0101 0000 shifting this to the right four times gives:

0010 1000 this is after a single shift

0001 0100 this is after two shifts

0000 1010 this is after three right shifts

0000 0101 and finally after four right shifts.

Notice how as the digits shifted to the right, we filled in the vacated positions on the left with zeros. The same thing happens if we shift to the left except that now the vacated positions will be on the right.

Maybe you want to swap hexadecimal digits and turn 0x5a into 0xa5. The example just now shows how to move 0x50 into 0x05. We didn’t actually need to mask out the other digit though. Because when shifting, you know that vacated spots get filled in with zeros but it’s also possible for digits to fall off the other side. Let me show you what happens if we shift 0x5a to the left this time by four shifts.

0101 1010 this is 0x5a before any shifts

1011 0100 this is after the first shift to the left

0110 1000 this is another shift to the left and the first one has dropped

1101 0000 this is the third left shift

1010 0000 after four left shifts, the “a” is now in the left digit and the “5” is gone.

*Related*