And bitwise operation gets 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 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?

asked on Stack Overflow Dec 15, 2014 by rnrneverdies

3 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

answered on Stack Overflow Dec 15, 2014 by Simba • edited Dec 15, 2014 by Keppil

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.

answered on Stack Overflow Dec 15, 2014 by mohsaied

The max value of "int" is 2^31-1. 0xF0000000 is a negative number. And any number with most significant bit equals to 1 is negative .

answered on Stack Overflow Dec 15, 2014 by Teng

User contributions licensed under CC BY-SA 3.0