How to mask byte value in Java?

bunkdeath picture bunkdeath · Jul 14, 2011 · Viewed 23.8k times · Source

My problem is some like this.

I have some calculation in byte in Java. In some calculation I get my desired result "2a" in byte value but in some calculation I get "ffffff9a" in byte value. I just want the "9a" value in from the result "ffffff9a". I tried this but didn't work.

byte a = (byte) b & 0xff;

where b have value "ffffff9a" byte value.

But while displaying the same process works like

System.out.println(Integer.toHexString(b & 0xff));

Where am I going wrong? What can I do to get my desired value?

Thanks


Actually I am trying to convert 8 bit character into gsm 7 bit. Also if someone there can help me through this, it would be helpful too. String is stored as a byte array and I have to convert this string or 8 bit bytes into 7 bit.

Answer

user166390 picture user166390 · Jul 14, 2011

The byte type in Java is signed. It has a range of [-128, 127].

System.out.println(Integer.toHexString(a & 0xff)); // note a, not b

Would show "the correct value" even though a, which is of type byte, will contain a negative value ((byte)0x92). That is, (int)a == 0x92 will be false because the cast to int keeps the value, negative and all, while (a & 0xff) == 0x92 will be true. This is because the bit-wise & promotes the expression to an int type while "masking away" the "sign bit" (not really sign bit, but artefact of two's complement).

See: Java How To "Covert" Bytes

Happy coding.