0

Can someone explain the following code snippet, please?

 methodAttributeLength = (long)dis.readUnsignedShort() << 16 | dis.readUnsignedShort();

I checked this in java doc .But I can't get the idea. I know what the java.io.DataInputStream.readUnsignedShort() method does.But the problem is that <<16 thing.

wi2ard
  • 1,471
  • 13
  • 24

1 Answers1

2

DataInputStream#readUnsignedShort return a int which spend 32 bits, but the short type spend 16 bits.

int << 16 will shift the low 16 bits to high 16 bits and fills 0 in the low 16 bits. for example:

int value = 0b11111111000000001000000011111111;
                              ^---------------     
                int high  = 0b10000000111111110000000000000000;
                // high == value << 16  

in this case, and the | operator is joins high bits and low bits together. for example:

int high  = 0b10000000111111110000000000000000; 
int low   = 0b00000000000000001000000000000001; 
int value = 0b10000000111111111000000000000001;
// value == high | low;  

on the other hand, your protocol saving an int into two shorts which are a high short and a low short. and the code above is read the int value from two shorts.

for more details you can see bitewise operators and shift operators.

holi-java
  • 29,655
  • 7
  • 72
  • 83
  • Can't we use `readInt()` for this purpose since it reads 4 bytes? –  May 21 '17 at 11:47
  • @Pegusus yes, `readInt` will read 4 bytes, however `readUnsignedShort` will read 2 bytes. and the `readInt` will result in negative numbers sometimes, but `readUnsignedShort` is never. – holi-java May 21 '17 at 11:50