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.
<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:
<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!