The PID is 13 bits long.
The buffer buf
is a byte
array. Each element is 8 bits.
The smallest Java integer type to hold a PID is the short
(16-bit signed integer). buf[1] << 8
promotes the byte
to an int
(4 bytes) while shifting so you now have enough space to hold the result.
buf[1] = XXXXXXXX
buf[2] = YYYYYYYY
buf[1] << 8
shifted 8 positions to the left in a 32-bit int
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X X X X X 0 0 0 0 0 0 0 0|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
(buf[1] << 8) | buf[2]
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X X X X X Y Y Y Y Y Y Y Y|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
((buf[1] << 8) | buf[2]) & 0x1fff
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X X Y Y Y Y Y Y Y Y|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
buf[2] & 0xff
is needed because in Java all bytes are signed and you need the unsigned int
value of the byte. Finally the whole thing is masked with 0x1fff
to keep the relevant 13 bits. If you want a short
you must cast the resulting int
.