Question
How can I convert a long to a byte array and then convert it back to a long in Java?
public static byte[] longToByteArray(long value) {
return new byte[] {
(byte)(value >> 56),
(byte)(value >> 48),
(byte)(value >> 40),
(byte)(value >> 32),
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)(value)
};
}
public static long byteArrayToLong(byte[] bytes) {
return (((long)bytes[0] << 56) |
((long)(bytes[1] & 255) << 48) |
((long)(bytes[2] & 255) << 40) |
((long)(bytes[3] & 255) << 32) |
((long)(bytes[4] & 255) << 24) |
((long)(bytes[5] & 255) << 16) |
((long)(bytes[6] & 255) << 8) |
((long)(bytes[7] & 255)));
}
Answer
In Java, converting a long to a byte array and subsequently back to a long can be useful for data transmission, especially over TCP connections. The byte array serves as a compact format for sending the numeric value. This guide will illustrate how you can perform these conversions effectively.
// Function to convert a long to a byte array
public static byte[] longToByteArray(long value) {
return new byte[] {
(byte)(value >> 56),
(byte)(value >> 48),
(byte)(value >> 40),
(byte)(value >> 32),
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)(value)
};
}
// Function to convert a byte array back to a long
public static long byteArrayToLong(byte[] bytes) {
return (((long)bytes[0] << 56) |
((long)(bytes[1] & 255) << 48) |
((long)(bytes[2] & 255) << 40) |
((long)(bytes[3] & 255) << 32) |
((long)(bytes[4] & 255) << 24) |
((long)(bytes[5] & 255) << 16) |
((long)(bytes[6] & 255) << 8) |
((long)(bytes[7] & 255)));
}
Causes
- Need to transmit data over a network efficiently.
- Conforming to certain data formats that require byte arrays.
- Simple storage of numeric values.
Solutions
- Use bitwise operations to convert a long to a byte array.
- Construct a long from a byte array using bitwise operations.
Common Mistakes
Mistake: Not handling the endianess of the data properly.
Solution: Ensure that both ends of the communication agree on the byte order (big-endian or little-endian).
Mistake: Using an incorrect array length when receiving the byte array.
Solution: Always validate the length of the byte array before converting back to long.
Helpers
- convert long to byte array in Java
- Java TCP byte array conversion
- long byte array Java example
- Java data transmission long byte array