整数をバイト配列に変換する (Java) 質問する

整数をバイト配列に変換する (Java) 質問する

Integerを に変換する最も簡単な方法は何ですかByte Array?

例えば0xAABBCCDD => {AA, BB, CC, DD}

ベストアンサー1

見てみましょうバイトバッファクラス。

ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xAABBCCDD);

byte[] result = b.array();

バイト順序を設定するとresult[0] == 0xAA、、、result[1] == 0xBBが保証さresult[2] == 0xCCれますresult[3] == 0xDD

または、手動で行うこともできます:

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 /*>> 0*/);

  return result;
}

しかし、このByteBufferクラスはそのような汚い作業のために設計されました。実際、 private は、java.nio.Bits以下で使用されるヘルパー メソッドを定義します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); }

おすすめ記事