Home  >  Article  >  Java  >  How do I convert between byte arrays and integers in Java?

How do I convert between byte arrays and integers in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 07:46:02383browse

How do I convert between byte arrays and integers in Java?

Converting Between Byte Arrays and Integers in Java

When dealing with binary data or passing values between systems, converting between byte arrays and integers becomes essential. This article delves into the straightforward process of achieving this conversion in Java.

The ByteBuffer class, located in the java.nio package, provides an efficient way to handle byte manipulation. It simplifies the conversion between byte arrays and various numeric types.

Byte Array to Integer

To convert a byte array into an integer, use the getShort method of ByteBuffer:

<code class="java">byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); </code>

The wrapped ByteBuffer is created from the input byte array. By default, Java assumes big-endian ordering, where the leftmost byte represents the most significant bit. Alternatively, for little-endian ordering, use getIntLittleEndian.

Integer to Byte Array

To convert an integer into a byte array, leverage the putShort method of ByteBuffer:

<code class="java">ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num); 
byte[] bytes = dbuf.array(); </code>

Example

Consider an integer 1. When converted to a byte array, it becomes {0x00, 0x01}. This is because 1 is a 16-bit unsigned integer in binary form, and each byte represents 8 bits. The leftmost byte stores the most significant bits (0x00) and the rightmost byte contains the least significant bits (0x01).

The above is the detailed content of How do I convert between byte arrays and integers in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn