Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned short in Java

How can I declare an unsigned short value in Java?

like image 354
maiky Avatar asked Dec 03 '09 17:12

maiky


People also ask

What is unsigned short in Java?

An unsigned shortA short is always signed in Java, but nothing prevents you from viewing a short simply as 16 bits and interpret those bits as a value between 0 and 65,535. Java short value. Bits. Interpreted as unsigned.

What is a unsigned short?

unsigned short is an unsigned integer type with the range 0 to USHRT_MAX , which is at least +65535. It can also be called short unsigned . Use %u , %o , %x or %X with printf to print an unsigned short .

Is there unsigned short?

No, really there is no such method, java is a high-level language. That's why Java doesn't have any unsigned data types.


2 Answers

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.

like image 60
Jon Skeet Avatar answered Sep 28 '22 04:09

Jon Skeet


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.

like image 40
starblue Avatar answered Sep 28 '22 03:09

starblue