Hi
how can i declare an unsigned short value in Java?
Thank you
Hi
how can i declare an unsigned short value in Java?
Thank you
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, as char
is clearly meant to be for text.
Java does not have unsigned types. What do you need it for?
Java does have the 'byte' data type, however.
Yep no such thing if you want to use the value in code vs. bit operations.
You can use a char, as it is an unsigned 16 bit value (though technically it is a unicode character so could potnetially change to be a 24 bit value in the future)... the other alternative is to use an int and make sure it is within range.
Don't use a char - use an int :-)
And here is a link discussing Java and the lack of unsigned.
You can code yourself up a ShortUnsigned
class and define methods for those operators you want. You won't be able to overload +
and -
and the others on them, nor have implicit type conversion with other primitive or numeric object types, alas.
Like some of the other answerers, I wonder why you have this pressing need for unsigned short that no other data type will fill.
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.