Explain Codes LogoExplain Codes Logo

How do I convert Long to byte

java
endianness
bitwise-operations
performance-benchmarking
Nikita BarsukovbyNikita Barsukov·Nov 28, 2024
TLDR

Quickly convert a Long to a byte[] using ByteBuffer:

byte[] bytes = ByteBuffer.allocate(Long.BYTES).putLong(12345L).array();

And revert to Long from byte[] just as efficiently:

Long restored = ByteBuffer.wrap(bytes).getLong();

This capitalizes on the ByteBuffer's built-in methods for seamless conversions, ensuring correctness and less cluttered code.

Delving into endianness

When converting between byte arrays and numeric types like Long, endianness is an essential factor to note. It delineates the byte significance order for storing multi-byte data types. In Java, you can specify endianness using ByteBuffer's order() method:

ByteBuffer byteBuffer = ByteBuffer.allocate(Long.BYTES); byteBuffer.order(ByteOrder.BIG_ENDIAN); // or ByteOrder.LITTLE_ENDIAN if you fancy byteBuffer.putLong(12345L); byte[] bytes = byteBuffer.array();

Note: Ensure uniformity in endianness when reading and writing data to avoid any spooky data corruption!

Road less travelled: Manual conversion

At times, manual conversion through bitwise operations can save the day when ByteBuffer seems cumbersome. Here's how you can save the princess:

public static byte[] longToBytes(long l) { byte[] result = new byte[8]; for (int i = 7; i >= 0; i--) { result[i] = (byte)(l & 0xFF); // Bit masking, ninja-style! 🥷 l >>= Byte.SIZE; } return result; } public static long bytesToLong(byte[] b) { long result = 0; for (int i = 0; i < 8; i++) { result <<= Byte.SIZE; result |= (b[i] & 0xFF); // More masking. It's a masquerade! 🎭 } return result; }

This nitty-gritty manipulation offers optimization, especially when ByteBuffer's overhead starts feeling like a heavy backpack.

Trekking through data streams

Steering long values over networks or working with IO streams? Meet your new friends, DataOutputStream and DataInputStream:

// Broadcasting a long far and wide DataOutputStream dos = new DataOutputStream(new ByteArrayOutputStream()); dos.writeLong(12345L); // Long goes brrrrrr.... // Eavesdropping on a byte stream DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes)); Long value = dis.readLong(); // I've got your long, byte stream!

No need for unfancy conversions; the stream handles the byte array wizardry inherently.

Libraries: When to rent a bulldozer

Guava and other libraries can become your bulldozers when you're exhausted of shovelling manually. They perform conversions neatly, plus they're fancy. Check out the Guava express:

byte[] bytes = Longs.toByteArray(12345L); // Guava style, like pineapple on pizza. 🍕

Balancing between code simplicity, readability, and the extra weight of libraries can seem tricky. But hey, who said programming was easy!

Comparing performance: Drag race!

It's time for a drag race! Benchmarks help determine who crosses the finish line first - ByteBuffer with its bells and whistles, manual bitwise shenanigans, or smooth operators like Guava:

// Assemble the competitors: ByteBuffer vs. manual vs. library methods // Ready, set, benchmark!

Ensure to achieve the sweet balance between lightning speed, readability, and maintainability. Speed is tempting, but so is clean, understandable code!

Ensuring data safety

Regardless of the conversion method, data integrity stands paramount. Right handling of endianness and a quick flip when required keeps the data chef happy! Make cooking conversion errors a taboo by religiously validating results and testing edge cases:

// Spoonful of unit tests make the code bugs stay away!