"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Convert Integers to Byte Arrays in Java?

How to Efficiently Convert Integers to Byte Arrays in Java?

Published on 2024-11-15
Browse:215

How to Efficiently Convert Integers to Byte Arrays in Java?

Efficient Conversion of Integers to Byte Arrays in Java

Converting an integer to a byte array can be useful for various purposes, such as network transmissions or data storage. There are multiple approaches to achieve this conversion.

ByteBuffer Class:

One efficient method is using the ByteBuffer class. ByteBuffer is a buffer that stores binary data and provides various operations to manipulate it. To convert an integer to a byte array using ByteBuffer:

ByteBuffer b = ByteBuffer.allocate(4); // Allocate a 4-byte buffer
b.putInt(0xAABBCCDD); // Write the integer value to the buffer

byte[] result = b.array(); // Retrieve the byte array from the buffer

Here, the byte order of the buffer ensures that the bytes are arranged in the correct order.

Manual Conversion:

Alternatively, you can manually convert the integer to a byte array:

byte[] toBytes(int i) {
  // Create a new byte array of length 4
  byte[] result = new byte[4];
  
  // Shift bits and assign to each byte
  result[0] = (byte) (i >> 24);
  result[1] = (byte) (i >> 16);
  result[2] = (byte) (i >> 8);
  result[3] = (byte) i;
  
  return result;
}

This approach requires explicit bit-shifting and assignment to each byte.

Helper Methods in java.nio.Bits:

The ByteBuffer class utilizes internal helper methods defined in the java.nio.Bits class:

private static byte int3(int x) { return (byte)(x >> 24); }
private static byte int2(int x) { return (byte)(x >> 16); }
private static byte int1(int x) { return (byte)(x >>  8); }
private static byte int0(int x) { return (byte)(x >>  0); }

These methods simplify the bit-shifting operations mentioned above.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3