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

15,833

Solution 1

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.

Solution 2

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

System.out.println("signed s=" + s + ", unsigned s=" + Short.toUnsignedInt(s))
Share:
15,833

Related videos on Youtube

Nate Lockwood
Author by

Nate Lockwood

I work at a US federal laboratory and participate in research using an aircraft with several imaging radiometers (research grade cameras with band pass filters and other modifications) so that we can acquire synchronized images - mostly infrared. Our main research thrust is studying wildfires. I'm in a project to upgrade our equipment, computer, and system. Since our contract engineer doesn't know C/C++ I've been teaching myself Java, HTML5, CSS3, and Dart attempting write software to provide a operator's GUI which controls the other computers and cameras on the aircraft LAN. I'm now concentrating on R to, agglomerate data and provide statistic analysis and plots of our data. My title is Ecologist.

Updated on April 26, 2022

Comments

  • Nate Lockwood
    Nate Lockwood about 2 years

    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.

  • Nate Lockwood
    Nate Lockwood almost 8 years
    What a difference time makes.
  • scottb
    scottb about 3 years
    Quite effective, but less readable than Short.toUnsignedInt().
  • Jon Skeet
    Jon Skeet about 3 years
    @scottb: True - that only became available about four years after the answer was written though :)