eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)