问题

怎样快速方式将anInteger转换成aByte Array

e.g.0xAABBCCDD => {AA, BB, CC, DD}


#1 热门回答(195 赞)

看看theByteBufferclass。

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] == 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;
}

尽管如此,ByteBufferclass是为这种脏手任务而设计的。事实上,privatejava.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); }

#2 热门回答(32 赞)

UsingBigInteger

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

UsingDataOutputStream

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();
}

UsingByteBuffer

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

#3 热门回答(26 赞)

使用此功能它适用于我

public byte[] toByteArray(int value) {
    return new byte[] {
            (byte)(value >> 24),
            (byte)(value >> 16),
            (byte)(value >> 8),
            (byte)value};
}

它将int转换为字节值


原文链接