Home > Java > javaTutorial > body text

How to Convert Between Integers and Byte Arrays in Java?

Mary-Kate Olsen
Release: 2024-10-25 22:46:03
Original
990 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!