Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-11-09 12:07:02
Original
202 people have browsed it

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();
Copy after login

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

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

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

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!

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