Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to parse uint8 in java?

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?

like image 260
stackoverflow Avatar asked Dec 28 '12 14:12

stackoverflow


People also ask

What is UInt8 in Java?

Constructs a new 8-bit unsigned parameter. UInt8(IntegerParameter value) Constructs a new instance with the same value as in the passed IntegerParameter . UInt8(short value) Constructs a new 8-bit unsigned parameter.

How to convert a byte[] to String in Java?

Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .

How to use unsigned byte in Java?

Java doesn't have unsigned bytes (0 to 255). To make an unsigned byte, we can cast the byte into an int and mask (bitwise and) the new int with a 0xff to get the last 8 bits or prevent sign extension. byte aByte = -1; int number = aByte & 0xff; // bytes to unsigned byte in an integer.

How to convert byte array to integer in Java?

Byte Array to int and long. Now, let's use the BigInteger class to convert a byte array to an int value: int value = new BigInteger(bytes). intValue();


2 Answers

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

like image 192
Martijn Courteaux Avatar answered Oct 03 '22 05:10

Martijn Courteaux


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

like image 20
Prince John Wesley Avatar answered Oct 03 '22 04:10

Prince John Wesley