1. Overview
In this tutorial, we’ll explore different approaches to convert a byte array to a numeric value (int, long, float, double) and vice versa.
The byte is the basic unit of information in computer storage and processing. The primitive types defined in the Java language are a convenient way to manipulate multiple bytes at the same time. Therefore, there is an inherent conversion relationship between a byte array and primitive types.
Since the short and char types consist of only two bytes, they don’t need much attention. So, we will focus on the conversion between a byte array and int, long, float, and double types.
2. Using Shift Operators
The most straightforward way of converting a byte array to a numeric value is using the shift operators.
2.1. Byte Array to int and long
When converting a byte array to an int value, we use the << (left shift) operator:
int value = 0;
for (byte b : bytes) {
value = (value << 8) + (b & 0xFF);
}
Normally, the length of the bytes array in the above code snippet should be equal to or less than four. That’s because an int value occupies four bytes. Otherwise, it will lead to the int range overflow.
To verify the correctness of the conversion, let’s define two constants:
byte[] INT_BYTE_ARRAY = new byte[] {
(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE
};
int INT_VALUE = 0xCAFEBABE;
If we look closely at these two constants, INT_BYTE_ARRAY and INT_VALUE, we’ll find that they’re different representations of the hexadecimal number 0xCAFEBABE.
Then, let’s check whether this conversion is correct:
int value = convertByteArrayToIntUsingShiftOperator(INT_BYTE_ARRAY);
assertEquals(INT_VALUE, value);
Similarly, when converting a byte array to a long value, we can reuse the above code snippet with two modifications: the value‘s type is long and the length of the bytes should be equal to or less than eight.
2.2. int and long to Byte Array
When converting an int value to a byte array, we can use the >> (signed right shift) or the >>> (unsigned right shift) operator:
byte[] bytes = new byte[Integer.BYTES];
int length = bytes.length;
for (int i = 0; i < length; i++) {
bytes[length - i - 1] = (byte) (value & 0xFF);
value >>= 8;
}
In the above code snippet, we can replace the >> operator with the >>> operator. That’s because we only use the bytes that the value parameter originally contains. So, the right shift with sign-extension or zero-extension won’t affect the final result.
Then, we can check the correctness of the above conversion:
byte[] bytes = convertIntToByteArrayUsingShiftOperator(INT_VALUE);
assertArrayEquals(INT_BYTE_ARRAY, bytes);
When converting a long value to a byte array, we only need to change the Integer.BYTES into Long.BYTES and make sure that the type of the value is long.
2.3. Byte Array to float and double
When converting a byte array to a float, we make use of the Float.intBitsToFloat() method:
// convert bytes to int
int intValue = 0;
for (byte b : bytes) {
intValue = (intValue << 8) + (b & 0xFF);
}
// convert int to float
float value = Float.intBitsToFloat(intValue);
From the code snippet above, we can learn that a byte array can’t be transformed directly into a float value. Basically, it takes two separate steps: First, we transfer from a byte array to an int value, and then we interpret the same bit pattern into a float value.
To verify the correctness of the conversion, let’s define two constants:
byte[] FLOAT_BYTE_ARRAY = new byte[] {
(byte) 0x40, (byte) 0x48, (byte) 0xF5, (byte) 0xC3
};
float FLOAT_VALUE = 3.14F;
Then, let’s check whether this conversion is correct:
float value = convertByteArrayToFloatUsingShiftOperator(FLOAT_BYTE_ARRAY);
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
In the same way, we can utilize an intermediate long value and the Double.longBitsToDouble() method to convert a byte array to a double value.
2.4. float and double to Byte Array
When converting a float to a byte array, we can take advantage of the Float.floatToIntBits() method:
// convert float to int
int intValue = Float.floatToIntBits(value);
// convert int to bytes
byte[] bytes = new byte[Float.BYTES];
int length = bytes.length;
for (int i = 0; i < length; i++) {
bytes[length - i - 1] = (byte) (intValue & 0xFF);
intValue >>= 8;
}
Then, let’s check whether this conversion is correct:
byte[] bytes = convertFloatToByteArrayUsingShiftOperator(FLOAT_VALUE);
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
By analogy, we can make use of the Double.doubleToLongBits() method to convert a double value to a byte array.
3. Using ByteBuffer
The java.nio.ByteBuffer class provides a neat, unified way to translate between a byte array and a numeric value (int, long, float, double).
3.1. Byte Array to Numeric Value
Now, we use the ByteBuffer class to convert a byte array to an int value:
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.put(bytes);
buffer.rewind();
int value = buffer.getInt();
Then, we use the ByteBuffer class to convert an int value to a byte array:
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.putInt(value);
buffer.rewind();
byte[] bytes = buffer.array();
We should note that the above two code snippets follow the same pattern:
- First, we use the ByteBuffer.allocate(int) method to get a ByteBuffer object with a specified capacity.
- Then, we put the original value (a byte array or an int value) into the ByteBuffer object, such as buffer.put(bytes) and buffer.putInt(value) methods.
- After that, we reset the position of the ByteBuffer object to zero, so we can read from the start.
- Finally, we get the target value from the ByteBuffer object, using such methods as buffer.getInt() and buffer.array().
This pattern is very versatile, and it supports the conversion of long, float, and double types. The only modification we need to make is the type-related information.
3.2. Using an Existing Byte Array
Additionally, the ByteBuffer.wrap(byte[]) method allows us to reuse an existing byte array without creating a new one:
ByteBuffer.wrap(bytes).getFloat();
However, we should also note that the length of the bytes variable above is equal to or greater than the size of the target type (Float.BYTES). Otherwise, it will throw BufferUnderflowException.
4. Using BigInteger
The main purpose of the java.math.BigInteger class is to represent large numeric values that would otherwise not fit within a primitive data type. Even though we can use it to convert between a byte array and a primitive value, using BigInteger is a bit heavy for this kind of purpose.
4.1. 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();
Similarly, the BigInteger class has a longValue() method to convert a byte array to a long value:
long value = new BigInteger(bytes).longValue();
Moreover, the BigInteger class also has an intValueExact() method and a longValueExact() method. These two methods should be used carefully: if the BigInteger object is out of the range of an int or a long type, respectively, both methods will throw an ArithmeticException.
When converting an int or a long value to a byte array, we can use the same code snippet:
byte[] bytes = BigInteger.valueOf(value).toByteArray();
However, the toByteArray() method of the BigInteger class returns the minimum number of bytes, not necessarily four or eight bytes.
4.2. Byte Array to float and double
Although the BigInteger class has a floatValue() method, we can’t use it to convert a byte array to a float value as expected. So, what should we do? We can use an int value as an intermediate step to convert a byte array into a float value:
int intValue = new BigInteger(bytes).intValue();
float value = Float.intBitsToFloat(intValue);
In the same way, we can convert a float value into a byte array:
int intValue = Float.floatToIntBits(value);
byte[] bytes = BigInteger.valueOf(intValue).toByteArray();
Likewise, by taking advantage of the Double.longBitsToDouble() and Double.doubleToLongBits() methods, we can use the BigInteger class to convert between a byte array and a double value.
5. Using Guava
The Guava library provides us with convenient methods to do this kind of conversion.
5.1. Byte Array to int and long
Within Guava, the Ints class in the com.google.common.primitives package contains a fromByteArray() method. Hence, it’s fairly easy for us to convert a byte array to an int value:
int value = Ints.fromByteArray(bytes);
The Ints class also has a toByteArray() method that can be used to convert an int value to a byte array:
byte[] bytes = Ints.toByteArray(value);
And, the Longs class is similar in use to the Ints class:
long value = Longs.fromByteArray(bytes);
byte[] bytes = Longs.toByteArray(value);
Furthermore, if we inspect the source code of the fromByteArray() and toByteArray() methods, we can find out that both methods use shift operators to do their tasks.
5.2. Byte Array to float and double
There also exist the Floats and Doubles classes in the same package. But, neither of these two classes support the fromByteArray() and toByteArray() methods.
However, we can make use of the Float.intBitsToFloat(), Float.floatToIntBits(), Double.longBitsToDouble(), and Double.doubleToLongBits() methods to complete the conversion between a byte array and a float or double value. For brevity, we have omitted the code here.
6. Using Commons Lang
When we are using Apache Commons Lang 3, it’s a bit complicated to do these kinds of conversions. That’s because the Commons Lang library uses little-endian byte arrays by default. However, the byte arrays we mentioned above are all in big-endian order. Thus, we need to transform a big-endian byte array to a little-endian byte array and vice versa.
6.1. Byte Array to int and long
The Conversion class in the org.apache.commons.lang3 package provides byteArrayToInt() and intToByteArray() methods.
Now, let’s convert a byte array into an int value:
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
ArrayUtils.reverse(copyBytes);
int value = Conversion.byteArrayToInt(copyBytes, 0, 0, 0, copyBytes.length);
In the above code, we make a copy of the original bytes variable. This is because sometimes, we do not want to change the contents of the original byte array.
Then, let’s convert an int value into a byte array:
byte[] bytes = new byte[Integer.BYTES];
Conversion.intToByteArray(value, 0, bytes, 0, bytes.length);
ArrayUtils.reverse(bytes);
The Conversion class also defines the byteArrayToLong() and longToByteArray() methods. And, we can use these two methods to transform between a byte array and a long value.
6.2. Byte Array to float and double
However, the Conversion class doesn’t directly provide the corresponding methods to convert a float or double value.
Again, we need an intermediate int or long value to transform between a byte array and a float or double value.
7. Conclusion
In this article, we illustrated various ways to convert a byte array to a numeric value using plain Java through shift operators, ByteBuffer, and BigInteger. Then, we saw the corresponding conversions using Guava and Apache Commons Lang.
As usual, the source code for this tutorial can be found over on GitHub.