Java how to parse uint8 in java?

≯℡__Kan透↙ 提交于 2019-11-29 14:07:20

问题


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?


回答1:


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




回答2:


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




回答3:


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



回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/14071361/java-how-to-parse-uint8-in-java

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