Java how to parse uint8 in java?

眉间皱痕 提交于 2019-11-30 09:12:50

Simply read it as as a byte and then convert to an 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:

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 & number will treat the number as unsigned byte. But the resultant type is int

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

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

You can do something like this:

int value = eightBits & 0xff;

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!