Java – shift bit operator, shift by negative number

I encountered an interesting situation when using the bitwise shift operator If the second operand is negative, how does the bitwise move operation work

That is < B, "<" shifts the bit mode to the left by b bits in a But if B is negative, shouldn't it be an error at run time? I can successfully run the following code, but I don't understand how it works?

public static void bitwiseleftShift(char testChar)
{
    int val=testChar-'a';
    int result= 1<<val;
    System.out.println("bit wise shift of 1 with val="+val+" is "+result);
}

input

bitwiseleftShift('A');// ASCII 65
   bitwiseleftShift('0'); // ASCII 48

result

bit wise shift of 1 with val=-32 is 1
   bit wise shift of 1 with val=-49 is 32768

ASCII of "a" is 97 Can someone help me understand how this works?

Solution

Does not conform to the Java language specification section 15.19:

So, the transition of - 32 is actually the transition of 0, and the transition of - 49 is actually the result of the transition of 15, so you see the result

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>