我得到一个整数:1695609641
当我使用方法:
String hex = Integer.toHexString(1695609641);
system.out.println(hex);
给:
6510f329
但是我想要一个字节数组:
byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};
我怎么做这个?
我得到一个整数:1695609641
当我使用方法:
String hex = Integer.toHexString(1695609641);
system.out.println(hex);
给:
6510f329
但是我想要一个字节数组:
byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};
我怎么做这个?
当前回答
BigInteger.valueOf(1695609641).toByteArray()
其他回答
如果您正在使用apache-commons
public static byte[] toByteArray(int value) {
byte result[] = new byte[4];
return Conversion.intToByteArray(value, 0, result, 0, 4);
}
使用Java NIO的ByteBuffer非常简单:
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
输出:
0x65 0x10 0xf3 0x29
我的尝试:
public static byte[] toBytes(final int intVal, final int... intArray) {
if (intArray == null || (intArray.length == 0)) {
return ByteBuffer.allocate(4).putInt(intVal).array();
} else {
final ByteBuffer bb = ByteBuffer.allocate(4 + (intArray.length * 4)).putInt(intVal);
for (final int val : intArray) {
bb.putInt(val);
}
return bb.array();
}
}
用它你可以这样做:
byte[] fourBytes = toBytes(0x01020304);
byte[] eightBytes = toBytes(0x01020304, 0x05060708);
完整的类在这里:https://gist.github.com/superbob/6548493,它支持从short或long初始化
byte[] eightBytesAgain = toBytes(0x0102030405060708L);
使用番石榴:
byte[] bytearray = Ints.toByteArray(1695609641);
public static byte[] intToBytes(int x) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(x);
out.close();
byte[] int_bytes = bos.toByteArray();
bos.close();
return int_bytes;
}