Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Int to Unsigned Byte and Back

Tags:

java

int

byte

I need to convert a number into an unsigned byte. The number is always less than or equal to 255, and so it will fit in one byte.

I also need to convert that byte back into that number. How would I do that in Java? I've tried several ways and none work. Here's what I'm trying to do now:

int size = 5; // Convert size int to binary String sizeStr = Integer.toString(size); byte binaryByte = Byte.valueOf(sizeStr); 

and now to convert that byte back into the number:

Byte test = new Byte(binaryByte); int msgSize = test.intValue(); 

Clearly, this does not work. For some reason, it always converts the number into 65. Any suggestions?

like image 696
darksky Avatar asked Sep 13 '11 12:09

darksky


People also ask

Can we convert int to byte in Java?

The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).

How do you convert int to byte in Python?

An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.


2 Answers

A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:

int i = 234; byte b = (byte) i; System.out.println(b); // -22 int i2 = b & 0xFF; System.out.println(i2); // 234 
like image 69
JB Nizet Avatar answered Sep 22 '22 10:09

JB Nizet


Java 8 provides Byte.toUnsignedInt to convert byte to int by unsigned conversion. In Oracle's JDK this is simply implemented as return ((int) x) & 0xff; because HotSpot already understands how to optimize this pattern, but it could be intrinsified on other VMs. More importantly, no prior knowledge is needed to understand what a call to toUnsignedInt(foo) does.

In total, Java 8 provides methods to convert byte and short to unsigned int and long, and int to unsigned long. A method to convert byte to unsigned short was deliberately omitted because the JVM only provides arithmetic on int and long anyway.

To convert an int back to a byte, just use a cast: (byte)someInt. The resulting narrowing primitive conversion will discard all but the last 8 bits.

like image 37
Jeffrey Bosboom Avatar answered Sep 22 '22 10:09

Jeffrey Bosboom