Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

And bitwise operation gets negative value

Tags:

java

I have this code:

 int code = 0x92011202;
 int a = (code & 0xF0000000) >> 28;
 int b = (code & 0x0F000000) >> 24;
 // ..
 int n = (code & 0x0000000F);

But if most significant bit of code is equal to 1 (from 9 to F) a comes negative value. All other variables works fine.

Why this happen?

like image 556
rnrneverdies Avatar asked Sep 30 '22 05:09

rnrneverdies


People also ask

Can result of bitwise and be negative?

The result of bitwise-AND can be negative, e.g. (-1) & (-1) is definitely -1 . However, if either operand is nonnegative, the result must also be nonnegative. This is because in 2's complement representation, a negative number must have its 31st bit set, and a nonnegative number must have its 31st bit cleared.

How bitwise and works with negative numbers?

In the two's complement representation, a negative number is represented by the bit pattern corresponding to the bitwise NOT (i.e. the "complement") of the positive number plus one, i.e. to the ones' complement plus one.

Why is bitwise not negative?

Whether an integer is positive or negative (the sign of the integer) is stored in a dedicated bit, the sign bit. The bitwise NOT affects this bit, too, so any positive number becomes a negative number and vice versa.

How do you check if a number is negative using Bitwise operators?

The expression ( n & (1 << (BITS -1 )) is to check MSB bit and gives 1 if the number is negative.


1 Answers

This is explained in The Java Tutorials.

Specifically :

The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

Java uses 2s complement variables. The only aspect about 2s complements that you care about is that, if the leftmost bit is a 1, the number is negative. The signed bitshift maintains sign, so if code is negative to begin with, it stays negative after the shift.

To fix your program use >>> instead which is a logical bitshift, ignoring sign

like image 199
Simba Avatar answered Oct 03 '22 02:10

Simba