How do I convert Long to byte and back in java
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Converting a Java long to bytes and reconstructing it later comes up in binary protocols, file formats, caches, and database keys. The core rules are simple: a long is always 8 bytes, both sides must agree on byte order, and converting to a single byte is not the same as converting to a byte[].
First Clarify the Target Type
If the question literally means "convert long to byte", the answer is that only the lowest 8 bits survive. That is a narrowing conversion and it loses information.
That is not reversible. If you need to round-trip the full numeric value, you need a byte[] of length 8.
The Cleanest Option: ByteBuffer
For most applications, ByteBuffer is the clearest and safest solution.
ByteBuffer is a good default because it makes the 8-byte size explicit and keeps the code easy to read.
Endianness Matters
A byte array is only meaningful if the reader and writer agree on byte order. ByteBuffer uses big-endian by default. That is fine as long as both sides use the same order.
If you need little-endian, set it explicitly:
Many cross-language bugs come from one side writing little-endian bytes and the other side reading big-endian bytes.
Manual Bit Shifting
If you want full control or need to avoid ByteBuffer, manual shifting works well.
The mask & 0xFFL is important because Java bytes are signed. Without that mask, negative byte values can be sign-extended when widened to a larger integer type.
Primitive long Versus Wrapper Long
The binary conversion logic works on primitive long, but many APIs hand you a nullable Long. Handle that explicitly:
That is better than silently treating null as zero unless your format defines that behavior on purpose.
Test the Round Trip
Conversion code is tiny, so developers often skip tests. That is a mistake. Test at least:
- '
0L' - '
1L' - '
-1L' - '
Long.MAX_VALUE' - '
Long.MIN_VALUE'
Those values catch sign bugs, truncation bugs, and incorrect endianness quickly.
Common Pitfalls
- Casting a
longto a singlebyteand expecting to get the original value back. - Forgetting that a full
longrequires exactly 8 bytes. - Reading and writing with different byte orders.
- Reconstructing the value without masking signed bytes.
- Ignoring the possibility that a wrapper
Longmay benull.
Summary
- A full Java
longround trip requires an 8-byte array, not a singlebyte. - '
ByteBufferis the simplest approach for most code.' - Byte order must match on both sides of the conversion.
- Manual bit shifting works too, but keep the
& 0xFFLmask. - Validate array length and nullability so conversion failures are explicit.

