Gre*_*osz 225
看看ByteBuffer类.
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();
Run Code Online (Sandbox Code Playgroud)
设置字节顺序保证了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;
}
Run Code Online (Sandbox Code Playgroud)
该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); }
Run Code Online (Sandbox Code Playgroud)
Pas*_*ent 35
使用BigInteger:
private byte[] bigIntToByteArray( final int i ) {
BigInteger bigInt = BigInteger.valueOf(i);
return bigInt.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)
使用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();
}
Run Code Online (Sandbox Code Playgroud)
使用ByteBuffer:
public byte[] intToBytes( final int i ) {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(i);
return bb.array();
}
Run Code Online (Sandbox Code Playgroud)
Le *_*hau 29
使用此功能它适用于我
public byte[] toByteArray(int value) {
return new byte[] {
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)value};
}
Run Code Online (Sandbox Code Playgroud)
它将int转换为字节值
Pan*_*ang 15
对于int→ byte[],请使用toByteArray():
byte[] byteArray = Ints.toByteArray(0xAABBCCDD);
Run Code Online (Sandbox Code Playgroud)
结果是{0xAA, 0xBB, 0xCC, 0xDD}.
它的反面是:fromByteArray()或fromBytes()
int intValue = Ints.fromByteArray(new byte[]{(byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD});
int intValue = Ints.fromBytes((byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD);
Run Code Online (Sandbox Code Playgroud)
结果是0xAABBCCDD.
你可以使用BigInteger:
来自整数:
byte[] array = BigInteger.valueOf(0xAABBCCDD).toByteArray();
System.out.println(Arrays.toString(array))
// --> {-86, -69, -52, -35 }
Run Code Online (Sandbox Code Playgroud)
返回的数组具有表示数字所需的大小,因此它可以是大小为1,例如表示1.但是,如果传递int,则大小不能超过四个字节.
从字符串:
BigInteger v = new BigInteger("AABBCCDD", 16);
byte[] array = v.toByteArray();
Run Code Online (Sandbox Code Playgroud)
但是,如果第一个字节更高0x7F(如本例所示),则需要注意,BigInteger会在数组的开头插入一个0x00字节.这需要区分正值和负值.