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
Why this happen?
This is explained in The Java Tutorials.
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
The most significant bit of code represents the sign -- 0 means the number is positive and 1 means the number is negative.
If you just print out code you'll find that it's negative.
Because the shift operator takes into account the sign (it's a signed shift), a will get a negative value if code is negative.
User contributions licensed under CC BY-SA 3.0