This forum is now read-only. Please use our new forums at discuss.codecademy.com.
I don't quite understand the Shift Bitwise operators >> and <<
I don't understand how these two shift operators work. I'd be thankful for any help.
shift_right = 0b1100 shift_left = 0b1 shift_right = shift_right >> 2 shift_left = shift_left << 2 print bin(shift_right) #0b11 print bin(shift_left) #0b100
Remember that little trick we all taught in primary school when it comes to multiplying by 10, 100, 1000 etc. We shifted the numbers to the left by 1,2,3 decimal places. Dividing by 10, 100, 1000 etc was a rightward shift by 1,2 or 3.
So a bitwise shift to the left is like multiplying your binary number by 2,4,8,16 etc depending on how many bits you shifted it to the left. A bitwise shift to the right is a like a floor division by 2,4,8,16 etc depending on the number of bits you shifted you number to the right.
shift_left was 1(in binary and decimal) you shifted it two places to the left, multiply by 4, 4 in binary is 100
shift_right was 1100(12 in decimal units) you shifted it two places to the right, division by 4 which gives you 3 in decimal units) 3 in binary form is 11
Note the position of the binary digits before and after the shifts.
0b1100 shifted by two bits to the right moves the
0s off the end and the two
1s to the right-most positions.
0b1 shifted by two bits to the left moves the
1 to the left by two places, and must fill in the two right-most bits with
Oh...thats how the code works! It sure is nice of codeacadamy to provide a decent example for this problem. Silly me, I figured that it would work by something like: slideright(>>2)
or even slideright = (>>2)
but no, once again, the instruction fail completely to define the actual problem. It sure is a good thing that there is such a huge database of help forms.