Home  >  Article  >  Java  >  How to Convert Between Integers and Byte Arrays in Java?

How to Convert Between Integers and Byte Arrays in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 22:46:03990browse

How to Convert Between Integers and Byte Arrays in Java?

Converting Bytes to Integers and Vice Versa in Java

Storing numerical data in byte arrays provides efficient storage and flexibility in various scenarios. To facilitate efficient data manipulation, it becomes necessary to convert between byte arrays and integer values.

Converting Integers to Byte Arrays

The goal is to represent an integer as a sequence of individual bytes. The ByteBuffer class in Java's java.nio package provides a convenient solution.

  • Create a ByteBuffer object using the allocate() method with the desired capacity for the array.
  • Use the putShort() method to write the integer into the byte buffer. It converts the integer to a short (16-bit integer) and stores it in the buffer.
  • Obtain the byte array from the byte buffer using the array() method. This array represents the integer as a sequence of bytes.
<code class="java">ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort((short) 1234);
byte[] byteArray = buffer.array();
// byteArray = { (byte) 4, (byte) 46 }</code>

Converting Byte Arrays to Integers

To retrieve the integer from the byte array, a similar process is reversed:

  • Create a ByteBuffer object using the wrap() method and provide the byte array as an argument.
  • Use the getShort() method to read the short value from the byte buffer, which will represent the recovered integer value.
<code class="java">ByteBuffer buffer = ByteBuffer.wrap(byteArray);
short num = buffer.getShort();
// num = 1234</code>

By utilizing the ByteBuffer class, you can efficiently convert between integers and byte arrays, ensuring reliable data representation and manipulation in your Java applications.

The above is the detailed content of How to Convert Between Integers and Byte Arrays 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