Emre801 Emre801 - 1 month ago 25
Java Question

How do I convert Long to byte[] and back in java

How do I convert a long to a byte[] and back in Java?
I'm trying convert a long to a byte[] so that I will be able to send the byte[] over a tcp connection. On the other side I want to take that byte[] and convert it back into a double.
Any tips would be appreciated.

Answer
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();//need flip 
    return buffer.getLong();
}

Or wrapped in a class to avoid repeatedly creating ByteBuffers:

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();//need flip 
        return buffer.getLong();
    }
}