Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when is it needed to cast hex literals in java to (byte)?

Tags:

java

casting

hex

For testing purposes, I tried to create an array like this:

byte[] expected = new byte[]{0x2f, 0x0d4, 0xe1, 0xc6, 0x7a, 0x2d, 0x28, 0xfc}

I expected, that java will complain and will ask me to cast every literal here to (byte), but unexpectedly, it asked me only to convert 0x4d, for example, but not 0x2f. The working example:

new byte[]{0x2f, (byte) 0xd4, (byte) 0xe1, (byte) 0xc6, 0x7a, 0x2d, 0x28, (byte) 0xfc}

How does that work?

like image 985
Illarion Kovalchuk Avatar asked Dec 10 '22 03:12

Illarion Kovalchuk


1 Answers

I suspect it is because the Java byte is signed, thus you have a range between -128 and 127. So all values >127 (0x80) have to be explicitly converted.

like image 67
Lanbo Avatar answered Dec 11 '22 16:12

Lanbo