Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a short as an unsigned short in Java

I have an array of short whose values range between 0 and the maximum value of a short. I scale the data (to display it as TYPE_USHORT) so that the resulting short values range between 0 and 65535. I need to print some of the scaled values but can't figure out how. The data are in an array and in a BufferedImage.

like image 975
Nate Lockwood Avatar asked Jun 30 '10 22:06

Nate Lockwood


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. 0.

Is there unsigned short?

The unsigned short type is the type ushort, which also has a size of 2 bytes. The minimum value is 0, the maximum value is 65 535.

What is an unsigned short?

It is the smallest (16 bit) integer data type in C++. Some properties of the unsigned short int data type are: Being an unsigned data type, it can store only positive values.


2 Answers

The simplest way is to convert to int:

short s = ...;
int i = s & 0xffff;

The bitmask is to make the conversion give a value in the range 0-65535 rather than -32768-32767.

like image 185
Jon Skeet Avatar answered Sep 29 '22 06:09

Jon Skeet


Since Java 1.8, the same can be done with Short.toUnsignedInt:

System.out.println("signed s=" + s + ", unsigned s=" + Short.toUnsignedInt(s))
like image 21
jurek sokolowski Avatar answered Sep 29 '22 06:09

jurek sokolowski