Pete Freitag Pete Freitag

Converting an unsigned byte array to an integer in Java

Updated on December 08, 2020
By Pete Freitag
java

I found myself today needing to deal with unsigned integers, and shorts in java. In Java there is no unsigned keyword like in C, or other languages. All primitives are signed (meaning they can hold negative values).

So I came up with two functions for converting the unsigned byte arrays into numbers I can use (thanks to Matt Finn, here at ActivSoftware for some pointers). I am posting these to help others, and to see if anyone knows of a more efficient or easier way to do this:

/**
 * Converts a 4 byte array of unsigned bytes to an long
 * @param b an array of 4 unsigned bytes
 * @return a long representing the unsigned int
 */
public static final long unsignedIntToLong(byte[] b) 
{
    long l = 0;
    l |= b[0] & 0xFF;
    l <<= 8;
    l |= b[1] & 0xFF;
    l <<= 8;
    l |= b[2] & 0xFF;
    l <<= 8;
    l |= b[3] & 0xFF;
    return l;
}
    
/**
 * Converts a two byte array to an integer
 * @param b a byte array of length 2
 * @return an int representing the unsigned short
 */
public static final int unsignedShortToInt(byte[] b) 
{
    int i = 0;
    i |= b[0] & 0xFF;
    i <<= 8;
    i |= b[1] & 0xFF;
    return i;
}

You will notice that the functions actually return a long for unsinged integers, and an integer for shorts, this is because we can't store a large unsigned int in a java int. You may also be interested to know that byte's, short's, and int's are all actually stored using 4 bytes by the jvm (so they can perform 32 bit operations).



java bytes jvm binary

Converting an unsigned byte array to an integer in Java was first published on November 29, 2004.

If you like reading about java, bytes, jvm, or binary then you might also like:

Weekly Security Advisories Email

Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).

Comments

A probably slower but more flexible way is:

int i = new BigInteger(1,bytes).intValue();

which takes any length array. Especially handy for doing IP filtering for both IPv4 and IPv6
by Lee Namba on 08/08/2005 at 9:22:29 AM UTC
i'm getting 145 in first byte, tht means 8th bit will be on, when it reaches after shifting on 32th bit, if cozez the signed bit to on, which changes the value...wht'll be the solutiion...thnx in adv
by ibraheem on 06/14/2006 at 7:27:40 AM UTC
There's a much easier way to do it:

to byte array - BigInteger.valueOf(num).toByteArray()

from byte array -
new BigInteger(array).intValue()
by Russell Harmon on 08/12/2008 at 4:50:37 PM UTC
Since java version 1.4, use of ByteBuffer makes these conversions easier, keeping the details of the conversion obfuscated. Unfortunately, when reading binary data files one must either know or be able to detect byte ordering, i.e. little/bin endian, for proper conversion.

For example;

import java.nio.ByteBuffer;

public class tt
{
static public void main(String[] args) throws Exception
{
byte[] buffer = new byte[55];

// Initialize a network byte order int to 1234
buffer[2] = (byte)0x04;
buffer[3] = (byte)0xD2;

// Use ByteBuffer.getInt() to "convert" the byte[] to int
int ival = ByteBuffer.wrap(buffer).getInt();

// Print out the value
System.out.println("length is " + ival);
} // public static void main(String[] args)
} // public class tt
by cj on 01/24/2009 at 9:07:58 AM UTC
You can use java.nio.ByteBuffer of you want to convert an array of bytes into a stream of integers.

ByteBuffer keyBuffer = ByteBuffer.wrap(rowByteArray);

try {
int nextInt = keyBuffer.getInt();
// do operations on the integer here
} catch(BufferUnderflowException e) {
// handle the last 3 bytes
}
by Amirisetty Vijayaraghavan on 05/01/2009 at 8:36:12 AM UTC
WHY TO WORRY GUYS..

1.FIRST CONVERT THE BYTE ARRAY TO STING.

2.THEN CONVERT THE STRING TO INTEGER.

EXAMPLE:

byte[] MyByteArray;

String Str = new
String(MyByteArray);

int Value = Integer.parseInt(Str);

Enjoy :)
by Kishor on 05/03/2011 at 12:13:01 AM UTC
Hi Pete,

I spent some time this weekend wrapping my head around what you're doing here. Nice work! It was a great mental exercise. :)

Take care,
-Aaron
by Aaron Neff on 07/09/2012 at 3:15:27 PM UTC