将整数转换为字节数组 (Java)
将 a 转换为 a 的快速方法是什么?Integer
Byte Array
例如:0xAABBCCDD => {AA, BB, CC, DD}
将 a 转换为 a 的快速方法是什么?Integer
Byte Array
例如:0xAABBCCDD => {AA, BB, CC, DD}
看看字节缓冲类。
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
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); }
用: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();
}