Search code examples
javajunitunsignedshort

Java - strange errors with unsigned values


There is 2-bytes array: private byte[] mData;

and method:

public void setWord(final short pData) {
        mData[0] = (byte) (pData >>> 8);
        mData[1] = (byte) (pData);
}

I wrote the simple test:

public void testWord() {
        Word word = new Word();
        word.setWord((short) 0x3FFF);

        Assert.assertEquals(0x3F, word.getByte(0));
        Assert.assertEquals(0xFF, word.getByte(1));
}

The second assert fails with message "Expected 255, but was -1". I know, that 0xFF signed short is, in fact, -1, but why JUnit thinks, that they are not equal? And, what is the correct way to implement such classes?


Solution

  • Java does not support unsigned types, so in order for a value to be 255, it must not be a signed byte, which is incapable of holding the value of 255. The 0xFF constant value will be taken as a signed int, and for the comparison, the byte value 0xFF will be converted to an int at -1 as well.

    You need to type cast the literal 0xFF to be a byte. Change the assert to be Assert.assertEquals((byte)0xFF, word.getByte(1)); Then the left hand side will evaluate to -1 as well as the right.