I am revising some of my learning resources and I have came across 2 examples that are somehow tricky for me.
1) The result of bitwise shift for an int value 0x80000000>>8 is 0x800000. How to make 8 shifts right when number of digits after 0x is equal to '8'?
2) The result of bitwise shift for an int value 0xff00<<8 is 0xff0000. How to make a proper bitwise 8 shifts left when number of digits after 0x is only equal to 6?
The binary equivalent of 0x80000000
is 10000000000000000000000000000000
.
So shifting it by 8 bits leads to a binary number 100000000000000000000000
which is 0x800000
.
The binary equivalent of 0xff00
is 0b1111111100000000
. Shifting it by 8 bits leads to 0b111111110000000000000000
.
The left shift and right shift actually work on the binary equivalent of the numbers and not on the hexadecimal equivalent. As you can see the binary equivalent has more digits than hexadecimal equivalent.
However suppose we were to do 0x80000000 >> 100
then 100 shifts would be more than the number of binary digits, so the result would be 0x0
.
In the left shift case, additional zeros are added with each left shift operation.