将整数转换为字节数组 (Java)

2022-08-31 07:42:13

将 a 转换为 a 的快速方法是什么?IntegerByte 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] == 0xAAresult[1] == 0xBBresult[2] == 0xCCresult[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;
}

不过,该类是为这种肮脏的手任务而设计的。实际上,私有定义了这些帮助器方法,这些方法由 :ByteBufferjava.nio.BitsByteBuffer.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); }

答案 2

用:BigInteger

private byte[] bigIntToByteArray( final int i ) {
    BigInteger bigInt = BigInteger.valueOf(i);      
    return bigInt.toByteArray();
}

用:DataOutputStream

private byte[] intToByteArray ( final int i ) throws IOException {      
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    dos.writeInt(i);
    dos.flush();
    return bos.toByteArray();
}

用:ByteBuffer

public byte[] intToBytes( final int i ) {
    ByteBuffer bb = ByteBuffer.allocate(4); 
    bb.putInt(i); 
    return bb.array();
}