Home  >  Article  >  Java  >  How to Efficiently Convert an Integer to a Byte Array in Java?

How to Efficiently Convert an Integer to a Byte Array in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 12:07:02203browse

How to Efficiently Convert an Integer to a Byte Array in Java?

Converting an Integer to a Byte Array in Java

To convert an integer into a byte array efficiently, consider using Java's ByteBuffer class.

ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(0xAABBCCDD);
byte[] result = b.array();

This ensures that result[0] contains the highest byte (0xAA), while result[3] contains the lowest byte (0xDD).

Alternatively, you can perform the conversion manually:

public static byte[] toBytes(int i) {
  byte[] result = new byte[4];
  result[0] = (byte) (i >>> 24);
  result[1] = (byte) (i >>> 16);
  result[2] = (byte) (i >>> 8);
  result[3] = (byte) i;
  return result;
}

The ByteBuffer class offers helper methods, like int3(), for performing these operations more efficiently:

private static byte int3(int x) { return (byte) (x >>> 24); }

The above is the detailed content of How to Efficiently Convert an Integer to a Byte Array 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