Nate Lockwood Nate Lockwood - 2 years ago 145
Java Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download