How to Convert a Long to byte[] and Back to Long in Java

Question

How can I convert a long to a byte array and then convert it back to a long in Java?

public static byte[] longToByteArray(long value) {
    return new byte[] {
        (byte)(value >> 56),
        (byte)(value >> 48),
        (byte)(value >> 40),
        (byte)(value >> 32),
        (byte)(value >> 24),
        (byte)(value >> 16),
        (byte)(value >> 8),
        (byte)(value)
    };
}

public static long byteArrayToLong(byte[] bytes) {
    return (((long)bytes[0] << 56) | 
            ((long)(bytes[1] & 255) << 48) | 
            ((long)(bytes[2] & 255) << 40) | 
            ((long)(bytes[3] & 255) << 32) | 
            ((long)(bytes[4] & 255) << 24) | 
            ((long)(bytes[5] & 255) << 16) | 
            ((long)(bytes[6] & 255) << 8) | 
            ((long)(bytes[7] & 255))); 
}

Answer

In Java, converting a long to a byte array and subsequently back to a long can be useful for data transmission, especially over TCP connections. The byte array serves as a compact format for sending the numeric value. This guide will illustrate how you can perform these conversions effectively.

// Function to convert a long to a byte array
public static byte[] longToByteArray(long value) {
    return new byte[] {
        (byte)(value >> 56),
        (byte)(value >> 48),
        (byte)(value >> 40),
        (byte)(value >> 32),
        (byte)(value >> 24),
        (byte)(value >> 16),
        (byte)(value >> 8),
        (byte)(value)
    };
}

// Function to convert a byte array back to a long
public static long byteArrayToLong(byte[] bytes) {
    return (((long)bytes[0] << 56) | 
            ((long)(bytes[1] & 255) << 48) | 
            ((long)(bytes[2] & 255) << 40) | 
            ((long)(bytes[3] & 255) << 32) | 
            ((long)(bytes[4] & 255) << 24) | 
            ((long)(bytes[5] & 255) << 16) | 
            ((long)(bytes[6] & 255) << 8) | 
            ((long)(bytes[7] & 255))); 
}

Causes

  • Need to transmit data over a network efficiently.
  • Conforming to certain data formats that require byte arrays.
  • Simple storage of numeric values.

Solutions

  • Use bitwise operations to convert a long to a byte array.
  • Construct a long from a byte array using bitwise operations.

Common Mistakes

Mistake: Not handling the endianess of the data properly.

Solution: Ensure that both ends of the communication agree on the byte order (big-endian or little-endian).

Mistake: Using an incorrect array length when receiving the byte array.

Solution: Always validate the length of the byte array before converting back to long.

Helpers

  • convert long to byte array in Java
  • Java TCP byte array conversion
  • long byte array Java example
  • Java data transmission long byte array

Related Questions

⦿How to Configure Logging Levels in SLF4J-simple with API 1.7

Learn how to configure SLF4Jsimple logging levels for API 1.7 with stepbystep instructions and code snippets.

⦿How to Fix the 'Unable to Run mksdcard SDK Tool' Error on Ubuntu During Android Studio Installation

Learn how to resolve the Unable to run mksdcard SDK tool error when installing Android Studio on Ubuntu with this detailed guide.

⦿How to Select a Random Element from a HashSet or LinkedHashSet in Java?

Learn how to randomly select an element from a HashSet or LinkedHashSet in Java with clear examples and best practices.

⦿How to Access the Outer Class from an Anonymous Inner Class in Java?

Learn how to refer to the outer class from an anonymous inner class in Java with examples and best practices.

⦿Understanding the Difference Between Collection and List in Java

Explore the key differences between Collection and List in Java including usage scenarios and code examples for clarity.

⦿How to Append Elements from a Java 8 Stream to an Existing List?

Learn how to efficiently add elements from a Java 8 stream to an existing ArrayList using simple and effective techniques.

⦿How to Configure Timeout Settings in Retrofit Library?

Learn how to set timeout configurations in Retrofit for your Android app with expert tips and code examples.

⦿Do I Need to Close Both FileReader and BufferedReader in Java?

Learn whether to close both FileReader and BufferedReader in Java file handling to avoid resource leaks. Best practices and code examples are included.

⦿Why Are Charset Names Not Defined as Constants in Programming Languages?

Explore why charset names like utf8 arent constants and learn how to effectively manage character encodings in software development.

⦿Understanding the Differences Between Strong, Soft, Weak, and Phantom References in Java

Explore the distinctions between strong soft weak and phantom references in Java and learn when to use each type effectively.

© Copyright 2025 - CodingTechRoom.com