Java Bitwise AND operator

2

I'm trying to mask an integer in order to separate each byte individually like so:

     int a = (0xffffffff & 0xff000000) >> 24;
     int b = (0xffffffff & 0x00ff0000) >> 16;
     int c = (0xffffffff & 0x0000ff00) >> 8;
     int d = 0xffffffff & 0x000000ff;

b, c and d give the correct answer in this case, 255, however, a continues to give me -1 and other negative numbers no matter what I change it to, I even tried:

             int a = (0xefffffff & 0xff000000) >> 24;

and it gives me -17.

Does someone know how do I solve this problem so that in this boundary case a gives me 255 and other positive numbers?

java
bit-manipulation
mask

3 Answers

9

This is because of sign extension. If the top-most bit is 1, then >> shifts in 1s. This is to preserve the sign of the argument. You want to use >>> which always shifts in 0. Or, mask after the shift:

int a = (0xffffffff >> 24) & 0x000000ff;
answered on Stack Overflow Sep 13, 2012 by Sean Owen
2

You are doing a signed shift, so the sign is preserved.

int a = (0xffffffff & 0xff000000) >>> 24; // unsigned shift.

or

int a = 0xffffffff >>> 24; // unsigned shift and all the bottom bits are lost anyway
int b = (0xffffffff >>> 16) & 0xFF;
int c = (0xffffffff >>> 8) & 0xFF;
int d = 0xffffffff & 0xFF;
answered on Stack Overflow Sep 13, 2012 by Peter Lawrey
0

I think you need an unsigned shifting,

Try it this way...

(0xffffffff & 0xff000000) >>> 24

answered on Stack Overflow Sep 13, 2012 by Kumar Vivek Mitra

User contributions licensed under CC BY-SA 3.0