java Java如何在java中解析uint8?

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

Java how to parse uint8 in java?

javabit-manipulation

提问by stackoverflow

I have a uint8(unsigned 8 bit integer)coming in from a UDP packet. Java only uses signed primitives. How do I parse this data structure correctly with java?

我有一个来自 UDP 数据包的uint8 (无符号 8 位整数)。Java 只使用有符号的原语。如何用java正确解析这个数据结构?

回答by Martijn Courteaux

Simply read it as as a byte and then convert to an int.

只需将其作为字节读取,然后转换为 int。

byte in = udppacket.getByte(0); // whatever goes here
int uint8 = in & 0xFF;

The bitmask is needed, because otherwise, values with bit 8 set to 1 will be converted to a negative int. Example:

需要位掩码,否则,位 8 设置为 1 的值将转换为负整数。例子:

This:                                   10000000
Will result in: 11111111111111111111111110000000

So when you afterwards apply the bitmask 0xFF to it, the leading 1's are getting cancelled out. For your information: 0xFF == 0b11111111

因此,当您随后对其应用位掩码 0xFF 时,前导 1 将被抵消。供你参考:0xFF == 0b11111111

回答by Prince John Wesley

0xFF & numberwill treat the number as unsigned byte. But the resultant type is int

0xFF & number将数字视为无符号字节。但结果类型是int

回答by Peter Lawrey

You can store 8-bit in a byteIf you really need to converted it to an unsigned value (and often you don't) you can use a mask

您可以将 8 位存储在 abyte如果您确实需要将其转换为无符号值(通常您不需要),您可以使用掩码

byte b = ...
int u = b & 0xFF; // unsigned 0 .. 255 value

回答by Ted Hopp

You can do something like this:

你可以这样做:

int value = eightBits & 0xff;

The &operator (like all integer operators in Java) up-casts eightBitsto an int(by sign-extending the sign bit). Since this would turn values greater than 0x7f into negative intvalues, you need to then mask off all but the lowest 8 bits.

&运营商(如Java中的所有整数运算符)上强制转换eightBitsint(由符号位符号扩展)。由于这会将大于 0x7f 的int值转换为负值,因此您需要屏蔽除最低 8 位以外的所有位。

回答by Asik

You could simply parse it into a shortor an int, which have enough range to hold all the values of an unsigned byte.

您可以简单地将其解析为 ashort或 an int,它们有足够的范围来保存无符号字节的所有值。