+ 4
Help me to solve the code #0010
explain bitwise shift operator ( << , >>) in detail.. https://code.sololearn.com/cSOSzGu6K45z/?ref=app
15 Answers
+ 5
Every bit position is power of 2:
128 64 32 16 8 4 2 1
1 1 1 1 1 1 1 1
1111 1111 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255
1010 1010 = 0 + 2 + 0 + 8 + 0 + 32 + 0 + 128 = 170
Or easier:
- - - - 1010 = 2 + 8 = 10
1010 - - - - = 32 + 128 = 160
10 + 160 = 170
With '<<' you shift the bits left.
0001 << 1 = 0010 (1 -> 2)
0010 << 1 = 0100 (2 -> 4)
0100 << 1 = 1000 (4 -> 8)
1000 << 1 = 0001 0000 (8 -> 16)
0011 << 1 = 0110 (3 -> 6)
0011 << 2 = 1100 (3 -> 12)
0010 << 5 = 0100 0000 (2 -> 64)
With '>>' you shift the bits right.
1000 >> 2 = 0010 (8 -> 2)
1010 >> 1 = 0101 (10 -> 5)
1010 >> 2 = 0010 (10 -> 2)
1111 >> 1 = 0111 (15 -> 7)
As you can see from the examples, when you shift left, you gain 0 in the tail, but when you shift right, you loose the tail.
So about your example, the operations are from left to right as follows:
x = 5
x >> 2 << 5 -> 0101 >> 2 = 0001 << 5 = 0010 0000 = 32
Note that x contains 5, and it's never changed!
You can add: print(x), if you want to check that.
+ 5
watch this video.
https://youtu.be/frwqnS9ICxw
+ 5
@Roel
mathematics is also my favourite subject.
+ 4
@Roel
you are wrong watch the video which I suggest in comments.
+ 2
@Roel
It depends upon you how will you figure out any problem.đ
+ 1
@Roel what is 2^5..?
+ 1
@Roel @Jay Bhade see the answer of @Boris Batinkov and clear your concept..
0
it somehow prints 2^5?
0
2^1 =2
2^2 =4
2^3 =8
2^4 =16
2^5 =32
it is called the power of something if im correct
0
i watched the video and came to the same conclusion as first,. because if you put all the binarys to the right and after that to the left, evertyhing is the same as first
0
and my first theory can be proven to symply fill in the number (for example) 8, 2^8 = 256, and thats what will appear
0
that's right, i am good at math at school, so i always try to see if there is any kind of mathematical pattern in codes
0
âșđ
0
i see, but most importently understand how it works now
- 1
2**5