4

I am trying to shift 2 bytes into a short. These 2 bytes represent an unsigned short that in turn represents a port. I've tried multiple ways to shift these bytes into a short on java. However, I constantly fail to do this correctly.

These are the ways I've tried:

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

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

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

Max
  • 2,354
  • 2
  • 14
  • 27

2 Answers2

5

Any value that undergoes arithmetic in Java, is first cast to higher type which could cover both operands. Both of operands are cast to int if they are still smaller.

As a result, b is first cast to int and becomes 0xFFFFFFCC. Or-ing it with anything shifted by 8 bits to the left always keeps the mask 0xFFFFFF00 and therefore has no impact on result. Casting it to short just shrinks off the left 16 bits.

To resolve it, explicitly mask with 0xFF before doing the operation:

(short)(((a&0xFF)<<8)|(b&0xFF))
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
0

//Try this, since you cannot convert from int to byte:

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

//Output: r = 0x17CC