How to Convert Between Byte Arrays and Integers in Java

Question

What is the correct way to convert between byte arrays and integers in Java?

public static void main(String[] args) {
    int a = 123;
    byte[] aBytes = intToByteArray(a);
    int a2 = byteArrayToInt(aBytes);

    System.out.println(a);         // prints '123'
    System.out.println(aBytes);    // prints '[B@459189e1'
    System.out.println(a2);        // prints '123'
    System.out.println(intToByteArray(a2));  // prints '[B@459189e1'
}

Answer

In Java, converting integers to byte arrays and back can lead to discrepancies if not handled correctly. This guide provides a detailed explanation of how to perform this conversion accurately using custom functions, as well as common pitfalls and their solutions.

public static int byteArrayToInt(byte[] b) {
    int value = 0;
    for (int i = 0; i < 4; i++) {
        int shift = (4 - 1 - i) * 8;
        value += (b[i] & 0x000000FF) << shift;
    }
    return value;
}

public static byte[] intToByteArray(int a) {
    byte[] ret = new byte[4];
    ret[0] = (byte) (a & 0xFF);
    ret[1] = (byte) ((a >> 8) & 0xFF);
    ret[2] = (byte) ((a >> 16) & 0xFF);
    ret[3] = (byte) ((a >> 24) & 0xFF);
    return ret;
}

Causes

  • The byte array representation may not be interpreted correctly when converting back to an integer if the order of bytes is not handled appropriately.
  • Byte data type is signed in Java. When dealing with larger integers, this can cause unexpected results due to sign extension.

Solutions

  • Ensure that you are interpreting the byte array in the same order that it was created.
  • Use appropriate data size to avoid overflow and ensure the correct transformation from byte array to int.

Common Mistakes

Mistake: Not checking the size of the byte array before conversion.

Solution: Ensure that your byte array is exactly 4 bytes long before attempting to convert it to an integer.

Mistake: Assuming the byte order is the same during conversion.

Solution: Be consistent with your byte order (endianness) when converting both ways.

Helpers

  • Java byte array to int
  • int to byte array Java
  • Java byte array conversion
  • Java integer conversion
  • convert int to byte array
  • convert byte array to int in Java

Related Questions

⦿How to Implement a Median-Heap for Efficient Median Tracking

Learn how to implement a MedianHeap with efficient insert find median and delete median operations in Java using an arraybased approach.

⦿How to Identify the Correct java.exe Process to Terminate on Windows?

Learn how to identify and terminate the correct java.exe process on a Windows machine to troubleshoot misbehaving Java applications.

⦿How to Exclude Null Values When Using Spring Framework's BeanUtils to Copy Properties?

Learn how to effectively use Spring Frameworks BeanUtils to copy properties from one object to another while ignoring null values.

⦿How to Obtain an InputStream Using RestTemplate Instead of URL in Java?

Learn how to retrieve an InputStream with RestTemplate in Java replacing the traditional URL class usage. Optimize your HTTP calls efficiently.

⦿How to Resolve the 'Cannot call sendError() after the response has been committed' Exception in Tomcat?

Learn how to troubleshoot and fix the Cannot call sendError after the response has been committed exception in Apache Tomcat with detailed solutions and code examples.

⦿What is the Best IDE for Developing Swing Applications?

Discover the best IDEs for developing Java Swing applications including userfriendly options like IntelliJ IDEA and Eclipse.

⦿How to Use Toolbar with Fragments in Android ViewPager

Learn how to implement Toolbar with Fragments in Android ViewPager solve common issues and enhance your apps UI.

⦿How to Reverse Item Order in LinearLayoutManager Without Stacking from Bottom

Learn how to reverse RecyclerView items using LinearLayoutManager while ensuring items stack from the top instead of the bottom.

⦿How to Retrieve a Spring Bean Inside a Servlet Filter

Discover how to access Spring beans from a servlet filter in Java effectively with clear examples and solutions.

⦿How to Resolve "Unable to Find Instrumentation Info for: ComponentInfo{ }" Error in Android Espresso Tests?

Learn how to troubleshoot the Unable to find instrumentation info error in Android Espresso Testing with detailed solutions common mistakes and code snippets.

© Copyright 2025 - CodingTechRoom.com