And the bitwise operation gets a negative value

I have this code:

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

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

Why is this happening?

+5
source share
3 answers

This is explained in the Java Tutorials .

In particular:

The unsigned right shift operator "→>" shifts the zero to the leftmost position, and the leftmost position after "→" depends on the expansion of the sign.

Java uses 2s add-on variables. The only aspect about 2s that you are interested in is that if the leftmost bit is 1, the number is negative. The signed bitshift supports the sign, so if the code starts with a negative value, it remains negative after the shift.

To fix your program, use >>> instead, this is a logical bit-break, ignoring the sign

+5
source

The most significant bit of the code represents the sign - 0 means that the number is positive, and 1 means that the number is negative.

If you simply print the code, you will find that it is negative.

Since the shift operator takes into account the sign (this is a signed shift), a will receive a negative value if the code is negative.

0
source

The maximum value of "int" is 2 ^ 31-1. 0xF0000000 is a negative number. And any number with the most significant bit is 1, is negative.

-1
source

Source: https://habr.com/ru/post/1209052/


All Articles