Java integer to byte array
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Converting an int to a byte array in Java is usually a matter of choosing the right byte order and API. The two common approaches are ByteBuffer for clarity and manual bit shifting when you want explicit control.
What You Are Really Converting
A Java int is a 32-bit signed value, so the full conversion always involves 4 bytes.
That means if you want a complete representation, the output array length should be 4:
The next question is byte order, also called endianness.
The Cleanest Option: ByteBuffer
ByteBuffer is the standard library tool for this job.
This prints 1 2 3 4 because 16909060 is 0x01020304.
ByteBuffer defaults to big-endian order, which is often what you want for network protocols and many binary formats.
Changing Endianness
If you need little-endian order, say so explicitly.
Never assume the receiver expects the same byte order you happen to use locally. Binary bugs often come from mismatched endianness, not from the conversion code itself.
Manual Bit Shifting
If you want full control or want to avoid ByteBuffer allocation patterns in a hot path, manual shifting is straightforward.
This version produces big-endian output.
For little-endian, reverse the order:
Converting Back To An Integer
It is often useful to show the reverse operation too:
If you encode with a certain byte order, decode with the same one.
Signed Bytes In Java
Java's byte type is signed, which can surprise people when printing values. A byte with binary value 11111111 prints as -1, not 255.
That does not mean the conversion is wrong. If you want the unsigned numeric view for debugging, use:
That is why example code often prints (b & 0xFF) rather than b directly.
When To Use Which Approach
A practical rule is:
- use
ByteBufferfor readability and standard library correctness - use manual shifts when you need explicit control or are implementing a protocol by hand
In most application code, ByteBuffer is the clearer option.
Common Pitfalls
The most common mistake is forgetting to define the byte order. Two systems can both convert correctly and still disagree because one is big-endian and the other is little-endian.
Another mistake is printing signed byte values and assuming the negative output means corruption.
Developers also sometimes allocate arrays of the wrong size. A Java int always needs 4 bytes.
Finally, do not mix encoding and decoding styles casually. If the writer is little-endian and the reader assumes big-endian, the numbers will be wrong even though both sides use valid code.
Summary
- A Java
intconverts to 4 bytes. - '
ByteBufferis the standard and usually clearest approach.' - Java
ByteBufferdefaults to big-endian unless you change it. - Manual bit shifting is fine when you want explicit control.
- Always match byte order on both the writing and reading sides.

