Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Bitwise AND operator

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?

like image 993
Patricio Jerí Avatar asked Dec 01 '25 16:12

Patricio Jerí


1 Answers

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;
like image 112
Sean Owen Avatar answered Dec 03 '25 06:12

Sean Owen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!