• Post Reply Bookmark Topic Watch Topic
  • New Topic

readUnsignedShort() Method  RSS feed

 
Greenhorn
Posts: 1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one explain the following code snippet please?

methodAttributeLength = (long)dis.readUnsignedShort() << 16 | dis.readUnsignedShort();
 
Marshal
Posts: 56605
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I found six versions of readUnsignedShort() methods; that in the link appears to be equivalent to reading a char. Maybe dis is a DataInputStream (and maybe it is something different). Anyway, they all appear to read an int. If they are unsigned, then the rightmost sixteen bits will contain the value of the short and the leftmost sixteen bits will be 0000000... so you never get a negative result.
I presume you are familiar with the cast operator, the leftshift operator and the bitwise (inclusive) or operator. Their precedences are the same as the order I have named them in.
The cast has the highest precedence, so the int is cast to a long, whose leftmost 48 bits are now 0000... Again, never a negative result.
Then you shift the number sixteen bits left, which puts sixteen 0 bits on the right end and loses the leftmost sixteen bits into cyber‑limbo, where they are never seen again. In this instance it is exactly the same as multiplying by 2¹⁶. Still no negative numbers.
Then you read the next short, again as an int with sixteen 0 bits at its left end. Again never negative.
Then you use the bitwise or operator to make any places where there is a 1 bit in either number into a 1, only having 0 bits where both are 0. If you have the overlapping sixteen bits all 000..., you won't perceive any difference from the + operator.

That looks exactly the same as trying to read an unsigned int and cast it to a long, so please check whether there is a readUnsignedInt() method returning a long. If there isn't an unsignedInt method, you can probably read a signed int, cast it to a long, and use the bitwise and operator with −1 (as an int, not a long), which shou‍ld give the same result.
Alternatively, use ordinary signed integer datatypes and display them with the unsigned methods of the Math class or the Integer class, I forget which. Methods for unsigned arithmetic were introduced in Java8.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!