Java byte move returns unexpected result

I am trying to translate 2 bytes to short. These 2 bytes represent an unsigned short, which in turn represents a port. I tried several ways to shift these bytes to short in java. However, I am constantly not doing it right.

This is how I tried:

byte a = 0x17;
byte b = 0xCC;

(short)((a << 8) | b);
(short)(((short)a << 8) | b);

The result is 0xFFCC, but should be 0x17CC.

+4
source share
2 answers

Any value that undergoes arithmetic in Java is first carried over to a higher type, which can span both operands. Both operands are passed in intif they are even smaller.

b int 0xFFFFFFCC. , 8 , 0xFFFFFF00 , , . , 16 .

, 0xFF :

(short)(((a&0xFF)<<8)|(b&0xFF))
+5

// , int :

short a = 0x17; short b = 0xCC; System.out.println("r = " + String.format("0x%04X", (short)((a << 8) | b)));

//: r = 0x17CC

0

All Articles