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

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

Patricia Arquette
Release: 2024-11-23 11:43:53
Original
615 people have browsed it

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

Convert Integer into Byte Array (Java)

In Java, converting an Integer to a Byte Array can be achieved using various approaches. One efficient method involves employing the ByteBuffer class:

ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(0xAABBCCDD);

byte[] result = b.array();
Copy after login

In the code snippet above, the ByteBuffer's byte order is set to BIG_ENDIAN. As a result, result[0] contains the most significant byte (0xAA), followed by result[1] (0xBB), result[2] (0xCC), and result[3] (0xDD).

Alternatively, you can convert the integer manually:

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 provides optimized methods for such tasks. Notably, java.nio.Bits defines helper methods used by ByteBuffer.putInt():

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

These methods are designed to extract individual bytes from an integer efficiently.

The above is the detailed content of How to 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