How do I print a short as an unsigned short in Java
Asked Answered
H

2

18

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.

Haga answered 30/6, 2010 at 22:9 Comment(0)
L
35

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.

Lagos answered 30/6, 2010 at 22:20 Comment(2)
Quite effective, but less readable than Short.toUnsignedInt().Paneling
@scottb: True - that only became available about four years after the answer was written though :)Lagos
S
23

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

System.out.println("signed s=" + s + ", unsigned s=" + Short.toUnsignedInt(s))
Sidekick answered 19/6, 2016 at 12:19 Comment(1)
What a difference time makes.Haga

© 2022 - 2024 — McMap. All rights reserved.