Java
Long to byte[]
Data Conversion
Java Programming
Byte Array

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.

java
1public class NarrowingDemo {
2    public static void main(String[] args) {
3        long value = 300L;
4        byte b = (byte) value;
5
6        System.out.println(value); // 300
7        System.out.println(b);     // 44
8    }
9}

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.

java
1import java.nio.ByteBuffer;
2
3public class LongBytes {
4    public static byte[] toBytes(long value) {
5        return ByteBuffer.allocate(Long.BYTES)
6                .putLong(value)
7                .array();
8    }
9
10    public static long fromBytes(byte[] bytes) {
11        if (bytes.length != Long.BYTES) {
12            throw new IllegalArgumentException("Expected exactly 8 bytes");
13        }
14
15        return ByteBuffer.wrap(bytes).getLong();
16    }
17
18    public static void main(String[] args) {
19        long original = 1234567890123456789L;
20        byte[] encoded = toBytes(original);
21        long decoded = fromBytes(encoded);
22
23        System.out.println(original);
24        System.out.println(decoded);
25        System.out.println(original == decoded);
26    }
27}

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:

java
1import java.nio.ByteBuffer;
2import java.nio.ByteOrder;
3
4public class LittleEndianLongBytes {
5    public static byte[] toBytes(long value) {
6        return ByteBuffer.allocate(Long.BYTES)
7                .order(ByteOrder.LITTLE_ENDIAN)
8                .putLong(value)
9                .array();
10    }
11
12    public static long fromBytes(byte[] bytes) {
13        if (bytes.length != Long.BYTES) {
14            throw new IllegalArgumentException("Expected exactly 8 bytes");
15        }
16
17        return ByteBuffer.wrap(bytes)
18                .order(ByteOrder.LITTLE_ENDIAN)
19                .getLong();
20    }
21}

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.

java
1public class ManualLongBytes {
2    public static byte[] toBytes(long value) {
3        byte[] out = new byte[8];
4
5        for (int i = 7; i >= 0; i--) {
6            out[i] = (byte) (value & 0xFFL);
7            value >>>= 8;
8        }
9
10        return out;
11    }
12
13    public static long fromBytes(byte[] bytes) {
14        if (bytes.length != 8) {
15            throw new IllegalArgumentException("Expected exactly 8 bytes");
16        }
17
18        long result = 0L;
19        for (byte b : bytes) {
20            result = (result << 8) | (b & 0xFFL);
21        }
22        return result;
23    }
24}

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:

java
1public static byte[] toBytes(Long value) {
2    if (value == null) {
3        throw new IllegalArgumentException("value must not be null");
4    }
5
6    return java.nio.ByteBuffer.allocate(Long.BYTES)
7            .putLong(value.longValue())
8            .array();
9}

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 long to a single byte and expecting to get the original value back.
  • Forgetting that a full long requires exactly 8 bytes.
  • Reading and writing with different byte orders.
  • Reconstructing the value without masking signed bytes.
  • Ignoring the possibility that a wrapper Long may be null.

Summary

  • A full Java long round trip requires an 8-byte array, not a single byte.
  • 'ByteBuffer is the simplest approach for most code.'
  • Byte order must match on both sides of the conversion.
  • Manual bit shifting works too, but keep the & 0xFFL mask.
  • Validate array length and nullability so conversion failures are explicit.

Course illustration
Course illustration

All Rights Reserved.