Home  >  Article  >  Java  >  How to Convert a Long to a Byte Array and Back in Java?

How to Convert a Long to a Byte Array and Back in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 16:58:02368browse

How to Convert a Long to a Byte Array and Back in Java?

Convert Long to Byte Array and Back in Java

In Java, converting a long value to a byte[] and back can be a common requirement for various scenarios. Let's explore efficient ways to achieve this.

Converting Long to Byte Array

To convert a long to a byte[], we can utilize Java's ByteBuffer class. Here's a simple example:

<code class="java">public byte[] longToBytes(long x) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(x);
    return buffer.array();
}</code>

Converting Byte Array to Long

To convert the byte[] back to a long, we can use another instance of ByteBuffer:

<code class="java">public long bytesToLong(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.put(bytes);
    buffer.flip();
    return buffer.getLong();
}</code>

Note: In the above code, it's crucial to call buffer.flip() before retrieving the long value, as it switches the buffer from write to read mode.

Optimized Class-based Approach

To avoid creating multiple instances of ByteBuffer for repeated conversions, you can create a separate class like this:

<code class="java">public class ByteUtils {
    private static ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);

    public static byte[] longToBytes(long x) {
        buffer.putLong(0, x);
        return buffer.array();
    }

    public static long bytesToLong(byte[] bytes) {
        buffer.put(bytes, 0, bytes.length);
        buffer.flip();
        return buffer.getLong();
    }
}</code>

Endian-ness Considerations

When converting between long and byte[], you should consider the endian-ness of the system you're working with. Endian-ness refers to the order in which bytes are stored in memory (little-endian or big-endian). Java uses big-endian, so this aspect is handled automatically.

Alternative Approaches

There are alternative libraries like Guava that provide convenient methods for performing this type of conversion. However, the native Java solutions presented here can be efficient and reliable for most use cases.

The above is the detailed content of How to Convert a Long to a Byte Array and Back in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn