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>
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>
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!