How to convert Int to unsigned byte and vice versa

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

I also need to convert this byte back to this number. How do I do this in Java? I tried several ways and nobody works. Here is 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 this byte to a number:

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

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

+77
java int byte
Sep 13 2018-11-11T00:
source share
9 answers

A byte is always signed in Java. You can get its unsigned value using binary and with 0xFF, but:

 int i = 234; byte b = (byte) i; System.out.println(b); // -22 int i2 = b & 0xFF; System.out.println(i2); // 234 
+180
Sep 13 '11 at 12:10
source share

Java 8 provides Byte.toUnsignedInt converting byte to int unsigned conversion. In Oracle JDK, this is simply implemented as return ((int) x) & 0xff; , because HotSpot already understands how to optimize this template, but it can be integrated into other virtual machines. More importantly, no prior knowledge is required to understand what the call toUnsignedInt(foo) does.

In general, Java 8 provides methods for converting byte and short to unsigned int and long , and int unsigned long . The method of converting byte to unsigned short was intentionally omitted since the JVM only provides arithmetic for int and long .

To convert int back to byte just use cast: (byte)someInt . As a result, narrowing the primitive conversion will discard everything except the last 8 bits.

+41
Mar 18 '15 at 20:25
source share

If you just need to convert the expected 8-bit value from a signed int to an unsigned value, you can use a simple bit offset:

 int signed = -119; // 11111111 11111111 11111111 10001001 /** * Use unsigned right shift operator to drop unset bits in positions 8-31 */ int psuedoUnsigned = (signed << 24) >>> 24; // 00000000 00000000 00000000 10001001 -> 137 base 10 /** * Convert back to signed by using the sign-extension properties of the right shift operator */ int backToSigned = (psuedoUnsigned << 24) >> 24; // back to original bit pattern 

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

If you use something other than int as the base type, you will obviously need to adjust the offset: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Also note that you cannot use the byte type, so this will result in the value indicated by other respondents. The smallest primitive type you could use to represent an 8-bit unsigned value would be short .

+7
Jul 11 '13 at 6:57
source share

The call to Integer.toString(size) converted to a char representation of your integer, i.e. char '5' . The ASCII representation of this character is a value of 65.

First you need to parse the string to an integer value, for example. using Integer.parseInt to return the original int value.

As the bottom line for a signed / unsigned conversion, it is better to leave String from the image and use bit manipulation, as @JB suggests.

+3
Sep 13 '11 at 12:08
source share

The solution works fine (thanks!), But if you want to avoid casting and leave the low level work in the JDK, you can use DataOutputStream to write your int and DataInputStream to read them again. They are automatically processed as unsigned bytes, and then:

To convert int to binary bytes;

 ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); int val = 250; dos.write(byteVal); ... dos.flush(); 

Reading them back:

 // important to use a (non-Unicode!) encoding like US_ASCII or ISO-8859-1, // ie, one that uses one byte per character ByteArrayInputStream bis = new ByteArrayInputStream( bos.toString("ISO-8859-1").getBytes("ISO-8859-1")); DataInputStream dis = new DataInputStream(bis); int byteVal = dis.readUnsignedByte(); 

Esp. useful for processing binary data formats (e.g. flat message formats, etc.).

+2
May 03 '12 at 10:05 a.m.
source share

Handling bytes and unsigned integers using BigInteger:

 byte[] b = ... // your integer in big-endian BigInteger ui = new BigInteger(b) // let BigInteger do the work int i = ui.intValue() // unsigned value assigned to i 
+1
Nov 20
source share

If you want to use primitive wrapper classes, this will work, but all java types are signed by default.

 public static void main(String[] args) { Integer i=5; Byte b = Byte.valueOf(i+""); //converts i to String and calls Byte.valueOf() System.out.println(b); System.out.println(Integer.valueOf(b)); } 
0
Sep 13 '11 at 12:14
source share

With the exception of char , all other numeric data types in Java are signed.

As stated in the previous answer, you can get an unsigned value by doing and operations with 0xFF . In this answer, I am going to explain how this happens.

 int i = 234; byte b = (byte) i; System.out.println(b); // -22 int i2 = b & 0xFF; // This is like casting b to int and perform and operation with 0xFF System.out.println(i2); // 234 

If your machine is 32-bit, then 32-bit is required to store int data type values. byte needs only 8 bits.

The variable int i is represented in memory as follows (as a 32-bit integer).

 0{24}11101010 

Then the byte variable b is represented as:

 11101010 

Since byte not signed, this value represents -22 . (Find 2 add-ons to learn more about how to represent negative integers in memory)

Then, if you cast is to int it will still be -22 because the cast preserves the sign of the number.

 1{24}11101010 

The given 32-bit value of b executes and works with 0xFF .

  1{24}11101010 & 0{24}11111111 =0{24}11101010 

Then you will get 234 as an answer.

0
May 09 '19 at 5:20
source share

in Java 7

 public class Main { public static void main(String[] args) { byte b = -2; int i = 0 ; i = ( b & 0b1111_1111 ) ; System.err.println(i); } } 

result: 254

-one
Dec 31 '17 at 21:36
source share



All Articles