How do I convert Long to byte[] and back in 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();//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(); }}
Since this is getting so popular, I just want to mention that I think you're better off using a library like Guava in the vast majority of cases. And if you have some strange opposition to libraries, you should probably consider this answer first for native java solutions. I think the main thing my answer really has going for it is that you don't have to worry about the endian-ness of the system yourself.
You could use the Byte conversion methods from Google Guava.
Example:
byte[] bytes = Longs.toByteArray(12345L);
I tested the ByteBuffer method against plain bitwise operations but the latter is significantly faster.
public static byte[] longToBytes(long l) { byte[] result = new byte[8]; for (int i = 7; i >= 0; i--) { result[i] = (byte)(l & 0xFF); l >>= 8; } return result;}public static long bytesToLong(final byte[] b) { long result = 0; for (int i = 0; i < 8; i++) { result <<= 8; result |= (b[i] & 0xFF); } return result;}
For Java 8+ we can use the static variables that were added:
public static byte[] longToBytes(long l) { byte[] result = new byte[Long.BYTES]; for (int i = Long.BYTES - 1; i >= 0; i--) { result[i] = (byte)(l & 0xFF); l >>= Byte.SIZE; } return result;}public static long bytesToLong(final byte[] b) { long result = 0; for (int i = 0; i < Long.BYTES; i++) { result <<= Byte.SIZE; result |= (b[i] & 0xFF); } return result;}