Converting Long to Byte Array and Back in Java
In Java, converting a long primitive data type to a byte array (byte[]) and vice versa is a common task for various operations, such as sending data over a TCP connection. Here's a comprehensive solution to achieve this conversion:
Long to Byte Array
public byte[] longToBytes(long x) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(x);
return buffer.array();
}
This method uses the ByteBuffer class to create a buffer of size Long.BYTES, which is the number of bytes required to represent a long value. The putLong() method is used to write the long value into the buffer, and the array() method returns the underlying byte array representing the long.
Byte Array to Long
public long bytesToLong(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.put(bytes);
buffer.flip(); // Flip the buffer to prepare for reading
return buffer.getLong();
}
To convert the byte array back to a long, a new ByteBuffer is created and loaded with the given byte array. The flip() method is used to make the buffer ready for reading. Finally, the getLong() method reads the long value from the buffer.
Encapsulation in a Helper Class
For convenience, the conversion methods can be encapsulated in a utility class:
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(); // Flip the buffer to prepare for reading
return buffer.getLong();
}
}
This utility class provides a simple way to perform the conversion without having to create and manage ByteBuffer instances each time.
Endianness Considerations
Note that the ByteBuffer class uses the native endianness of the system. If cross-platform compatibility is required, additional considerations for handling endianness may be necessary.
Alternative Solution: Using Libraries
While the native Java solutions provided above are adequate, they can become tedious in certain scenarios. For complex or extended data conversion needs, consider using a library like Guava or Apache Commons, which provide more comprehensive and efficient solutions.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3