Question

There's something I'm struggling to understand, I have this piece of code :

public class HelloWorld{

public static int readByte(byte b) {
    return b & 0xFF;
}

public static short readShort(byte[] b) {
    return (short)(readByte(b[0]) | readByte(b[1]) << 8);
}

 public static void main(String []args){
    byte[] b = {(byte)0x94, 0x00};
    System.out.println(readShort(b));

 }
}

Now the result returned is 148, but I don't understand why if I remove the masking "& 0xFF", the result will change, if you're reading 1 byte at a time the masking of 0xFF doesn't suppose to affect the byte (that's what I know atleast), a friend of mine tried to explain me this and he said it's related to the byte "0x94" being unsigned and the casting going on in the readByte method but I couldn't understand it and I'm really having hard time to understand why you need the masking to read the byte properly, thanks in advance for anyone trying to help me !

Was it helpful?

Solution

A byte is signed data. So 0x94 is -108. When you return it as an int, you return -108 expanded to 4 bytes, which is NOT 0x94 (its FFFFFF94). That obviously screws up your later ORing. The mask fixes it because the byte 0x94 is converted to an int before ANDing it with 0xFF, so the AND will drop those extra 1s from the negative expansion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top