Unsigned short in Java
You can't, really. Java doesn't have any unsigned data types, except char
.
Admittedly you could use char
- it's a 16-bit unsigned type - but that would be horrible in my view, as char
is clearly meant to be for text: when code uses char
, I expect it to be using it for UTF-16 code units representing text that's interesting to the program, not arbitrary unsigned 16-bit integers with no relationship to text.
If you really need a value with exactly 16 bits:
Solution 1: Use the available signed short and stop worrying about the sign, unless you need to do comparison (<, <=, >, >=) or division (/, %, >>) operations. See this answer for how to handle signed numbers as if they were unsigned.
Solution 2 (where solution 1 doesn't apply): Use the lower 16 bits of int and remove the higher bits with & 0xffff where necessary.