Home > Java > javaTutorial > body text

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

Linda Hamilton
Release: 2024-11-04 21:27:02
Original
798 people have browsed it

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

Converting Long to Byte Array and Back in Java

When transmitting data over a TCP connection, it may be necessary to convert a long to a byte array. To achieve this conversion, you can leverage the following methods:

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

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

To avoid excessive creation of ByteBuffers, consider utilizing a class like the one below:

<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>
Copy after login

Remember, it's often preferable to employ a library like Guava for this task. However, for native Java solutions, these methods provide a reliable way to handle long-to-byte array conversions.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template