foreword
I recently encountered a question about bit operations in an interview
As shown below
May I ask aString
what is the printed value?
After learning bit operations, we all know that 9<<4 digits are expressed in binary system as 0000 1001.
If I follow my previous algorithm, it is 0000 10001. After 4 bit operations to the left, we get 1001 0000.
At this time, the value we get is 128+16 = 144
Get the value of 144, and then convert it to hexadecimal through the static method that comes with java toHexString(). Through the
hexadecimal conversion tool, we get 144 + 1 = 145, and the hexadecimal conversion is 91
illustrate
The answer to this question 91
is wrong! !
At that time, I was also confused and didn't know why I was wrong.
Finally, the interviewer told me that the answer was 120! But even if I know the answer, I don't know how it came from.
Then I wrote the test code and ran this function once, and the result was still 120.
I'm speechless now
reverse reasoning
We know that 120 in hexadecimal is the correct answer
, so how much is 120 in hexadecimal converted to decimal?
The result we got is 288
, which is 288. Let’s continue to use binary system to express it according to the base conversion to see what it looks like.
Binary: 1 0010 0000
256 32
This calculation is 256+32=288
Binary: 1 0010 0000 shifted five places to the left
Thus we can conclude
The above function 9<<4+1 is actually a bit operation after calculating 4+1 first.
Then to verify this reasoning, check the priority relationship between bit operations and arithmetic operations,
and get the following figure: