Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

java - Bit wise shift operator with shift by negative number

I came across an interesting scenario, When working with bitwise shift operator. If the second operand is negative, how does the bitwise shift operation works? .

i.e a << b , "<<" shifts a bit pattern to the left by b bits in a. But if b is neagtive, shouldn't it be an error at runtime ?

I am able to run the below code successfully 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 

Results

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

ASCII for 'a' is 97. Can someone help me understand how this works?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

But if b is neagtive, shouldn't it be an error at runtime?

Not according to the Java Language Specification, section 15.19:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

So a shift of -32 actually ends up as a shift of 0, and a shift of -49 actually ends up as a shift of 15 - hence the results you saw.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...