Java unsigned byte[2] 到 int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15560553/
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-31 20:03:42  来源:igfitidea点击:

Java unsigned byte[2] to int?

javatype-conversionbyte

提问by Eric Fossum

All I need to do is convert an unsigned two byte array to an integer. I know, I know, Java doesn't have unsigned data types, but my numbers are in pretend unsigned bytes.

我需要做的就是将一个无符号的两字节数组转换为一个整数。我知道,我知道,Java 没有无符号数据类型,但我的数字是假装无符号字节。

byte[] b = {(byte)0x88, (byte)0xb8}; // aka 35000
int i = (byte)b[0] << 8 | (byte)b[1];

Problem is that doesn't convert properly, because it thinks those are signed bytes... How do I convert it back to an int?

问题是不能正确转换,因为它认为那些是有符号字节......我如何将它转换回一个整数?

回答by rgettman

There are no unsigned numbers in Java, bytes or ints or anything else. When the bytes are converted to intprior to being bitshifted, they are sign-extended, i.e. 0x88=> 0xFFFFFF88. You need to mask out what you don't need.

Java 中没有无符号数、字节或整数或其他任何东西。当字节int在移位之前被转换为 时,它们被符号扩展,即0x88=> 0xFFFFFF88。你需要屏蔽掉你不需要的东西。

Try this

试试这个

int i = ((b[0] << 8) & 0x0000ff00) | (b[1] & 0x000000ff);

and you will get 35000.

你会得到 35000。

回答by Peter Lawrey

You can use

您可以使用

int i = ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);

or

或者

int i = ByteBuffer.wrap(b).getChar();

or

或者

int i = ByteBuffer.wrap(b).getShort() & 0xFFFF;