An easy way to look at bit shifting is to visually move the bits in the specified direction by the specified amount. If we have a bit string of 1000 and shift right by 1, we end up with 0100. Shift right by another 1 and we get 0010.
If we have 0010 and shift right by 2, however, we lose our bit! And there’s no getting it back after it falls of the beginning or end, so be careful! We’d end up with 0000.
So given some variable like my_bit_string = 0b1000, we can get 0b0001 by doing my_bit_string = my_bit_string >> 3.
Could someone explain the below statement as it confuses me a bit:
Shift operations are similar to rounding down after dividing and multiplying by 2 (respectively) for every time you shift, but it’s often easier just to think of it as shifting all the 1s and 0s left or right by the specified number of slots.
While the shift operations seem to be pretty easy to understand, I did not get the similarity between shifts and rounding.
“Slide to the Left! Slide to the Right!” exercise explanation is quite confusing, could someone help me out to understand it? Googling on similar topics did not help…
I kinda thought the same thing. This always has been confusing to me as well so i usually don’t even try this stuff out.
Here is a link to some Python documentation on this subject that might help you understand how it all works.
If this does not help i would advice to create a new topic under get help since it is a very good question in my opinion. And seeing this is your second post it should get more attention as its own post.
You pointed me to the right direction to search, in the Python docs there is a page that gives a better explanation, so it turns out to be very simple: https://wiki.python.org/moin/BitwiseOperators
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
So based on the binaries and shifting operations from exercise it will be like:
shouldn’t it be:
0b0010100 >> 3 == 0b0000010 (has one more 0 than the one in the example)
0b0000010 >> 2 == 0b0000000 (has one more 0 than the one in the example)