如何在 Java 中将 short 打印为未签名的 short

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3153787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:36:34  来源:igfitidea点击:

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

javaunsignedshortushort

提问by Nate Lockwood

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.

我有一个 short 数组,其值范围在 0 和一个 short 的最大值之间。我缩放数据(以将其显示为 TYPE_USHORT),以便得到的短值范围在 0 到 65535 之间。我需要打印一些缩放值,但不知道如何打印。数据位于数组和 BufferedImage 中。

回答by Jon Skeet

The simplest way is to convert to int:

最简单的方法是转换为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.

位掩码是为了使转换给出一个范围为 0-65535 而不是 -32768-32767 的值。

回答by jurek sokolowski

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

从 Java 1.8 开始,同样可以使用Short.toUnsignedInt

System.out.println("signed s=" + s + ", unsigned s=" + Short.toUnsignedInt(s))