Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 616
prashantsunkari Avatar asked Mar 24 '13 20:03

prashantsunkari


People also ask

Can you bit shift by a negative number?

The left shift and right shift operators should not be used for negative numbers. The result of is undefined behaviour if any of the operands is a negative number. For example results of both 1 >> -1 and 1 << -1 is undefined. If the number is shifted more than the size of integer, the behaviour is undefined.

How bitwise operations are applied on negative numbers?

The approach is quite simple: Use bitwise not to transform any negative integer into a non-negative integer, apply one of the functions 0–7, and then possibly apply bitwise not again to obtain the result.

What happens when you right shift a negative number?

Right Shifts For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used. The result of a right-shift of a signed negative number is implementation-dependent.

What is a negative shift?

that component of the readiness potential that precedes any conscious awareness of a wish to act.


1 Answers

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.

like image 112
Jon Skeet Avatar answered Oct 01 '22 02:10

Jon Skeet