+ 3
Explain me how does bitwise unsigned right shift operator works. ?? explain me https://code.sololearn.com/cw4k2w2j4NLc/?ref=app
3 Réponses
+ 2
With a signed right shift operator (>>) the left most bit is what will be added as the new left most bit when the shift occurs. So if we had a 4 bit type with the value of 1011 (-5) and right shifted it by one the new value would be 1101 (-3).
With an unsigned right shift operator (>>>) the left most bit will be zero filled regardless of the value of the left most bit. So again if we had the same 4 bit type with a value of 1011 (-5) and performed an unsigned right shift on it by one the new value would now be 0101 (5).
Keep in mind that the size of the type does matter. If you ran this in Java and used the type int which is 32bits the number (-5) would be 1 filled to the left of those four bits:
1111 1111 1111 1111 1111 1111 1111 1011
and when you unsigned right shift (>>>) this number becomes:
0111 1111 1111 1111 1111 1111 1111 1101
which is 2147483645
0
POSITIVE 6 bits - range = 0 to 63 =>64 numbers
000101 = 5 ( 1* 2^0 +1 + 1 * 2 ^ 2 = 5)
>>>1 = shift once right and fill with 0
100101 >>> 1 = 00010 ( first left one is moved out, second 1 moved one bit) equal with >>1 here
NEGATIVE 6 bits - range = -32 to 0 to 31 => 64 numbers
000101 = 5 (first is for sign 0 = pozitive)
1s complement is shift all bits = 111010
2s complement is +1 (simple) = 111011 = -5
(formula : 2s complent of number = -number)
2s complement of number + number = 000000 and 1 carry value which we ignore.
-5 >> 1 shift once = 111101 ( sign not affected, moving a bit make ones instead of zero)
1s complement is 111100
flip is 000011 = 3, results that is -3