Bitshifting is the practice of shifting all the columns of a binary number to the left or the right. The left-shift operator in languages with a C like syntax look like this << . The left-shift operator will shift the bits to the left in a variable n times, with a default shift of 1 place. This means 00001011 shifted to the left once will now be 00010110. This effectively doubled the numbers magnitude. What happens with a number like 1011 though? Shifted once to the left, this number would end up 0110. This is because the left-shift operator is not an end-around carry operator. The original number is lost. When using the left-shift operator, you may shift 1, 2,...n times to the left by the syntax N << timesToShift; where N is the variable to be shifted and timesToShift is the, you guessed it, the # of times the variable is to be shifted.
# To Shift: | Not Shifted | N << 1 | N << 2 | N << 3 |
Number | 10101100 | 01011000 | 10110000 | 01100000 |
This brings us the the right-shift. >>> The right-shift operator does the inverse of the left-shift. 101100 shifted once to the right would be 010011 all information shifted off the right is lost. The right-shift operator divides the number, if you right-shift once you have divided the number in half. If the number was an odd number, you are truncating the modulus.
# To Shift: | Not Shifted | N >>> 1 | N >>> 2 | N >>> 3 |
Number | 10101100 | 01010110 | 00101011 | 00010101 |
Ok, so what happens when we are using 2's compliment and trying to bitshift in this manor? We get funny results! They've already thought about this, the operator is the arithmatic-right-shift operator. >> This operator is not an end-around carry operator, but it does pad with the state of the most significant bit (the polarity bit). For instance this number: 10001110 shifted right arithmetically 3 times would be 11110001. There is not an arithmatic-left-shift operator because it would not produce a number you could not derive from the operators already given.
# To Shift: | Not Shifted | N >>> 1 | N >>> 2 | N >>> 3 |
Number | 10101100 | 11010110 | 11101011 | 11110101 |
# To Shift: | Not Shifted | N >>> 1 | N >>> 2 | N >>> 3 |
Number | 00101100 | 00010110 | 00001011 | 00000101 |