6. >> << Explanation


#1



https://www.codecademy.com/en/courses/python-intermediate-en-KE1UJ/1/1?curriculum_id=4f89dab3d788890003000096

I'm a bit confused with the explanation about the >> << bit operators, and I cannot find a good explanation online.

The example they give is this:

0b000001 << 2 == 0b000100 (1 << 2 = 4)
0b000101 << 3 == 0b101000 (5 << 3 = 40)

Right Bit Shift (>>)

0b0010100 >> 3 == 0b000010 (20 >> 3 = 2)
0b0000010 >> 2 == 0b000000 (2 >> 2 = 0)

In the example, the << operator keeps the same amount of digits, but the >> operator causes the loss of a digit (I assume because a "1" got taken off). However when I do the example I write this:

shift_right = 0b1100
shift_left = 0b1
shift_right_again = 0b0010100

Your code here!

shift_right = shift_right >> 2
shift_left = shift_left << 2
shift_right_again = shift_right_again >> 3

print bin(shift_right)
print bin(shift_left)
print bin(shift_right_again)

And get this:

0b11
0b100
0b10

Variable shift_right_again is asking the system to do the same thing the example showed us... move 0b0010100 to the right by 3, but I am getting 0b10 as the outcome. Even assuming all digits that go to the right disappear (which the example doesn't show), it should still be 0b0010. On top of that, if you look at the shift_right variable, from the example I would assume it would be 0b0011, but instead I got 0b11.

Note: I already completed the exercise, I'm just curious to how this operator works.

`


#2

i'm understanding the bitwise notation.

'>> 2 #shifts to the right, what you understand. the number is the amount of spots, units, digits that it shifts what is there.
i.e.
0b1000 >> 2 0b0010 #left the extra zeros there so you could see the result
(8 then to 2)
0b11 << 3 0b1100
(three then to 12)
'
think of the counts like this:
16 8 4 2 1

now make a chart with that across the top and start to fill in what you would need to count to say twenty
00001 => 1
00010 => 2
00100 => 4
01000 => 8
10000 => 16

once you do the 15 = 8 plus 4 plus 2 plus 1 --you will start to understand it better. 0b1111

what i really don't understand is what are they actually looking for in this exercise?
what do they want me to write out? what i'm going to be getting as results? what they are going to convert to?

hope i helped some


#3

so i figured out what they are looking for.

'#your code here'
write what you believe what it's supposed to be.
i.e.
shift_right blahblahblah

you don't have to do anything else with it.

check out https://en.wikipedia.org/wiki/Bitwise_operation this goes into some depth yet it's quite interesting and will give you a start( or more info) to what you want to learn.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.