我得到一个整数: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};
我怎么做这个?
当前回答
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;
}
其他回答
使用番石榴:
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;
}
如何:
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
这个主意不是我的。我是从dzone.com上的一些帖子上截取的。
我的尝试:
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);
因为一般情况下,你会想在稍后将这个数组转换回int类型,这里有一些方法可以将一个int类型的数组转换为字节类型的数组,反之亦然:
public static byte[] convertToByteArray(final int[] pIntArray)
{
final byte[] array = new byte[pIntArray.length * 4];
for (int j = 0; j < pIntArray.length; j++)
{
final int c = pIntArray[j];
array[j * 4] = (byte)((c & 0xFF000000) >> 24);
array[j * 4 + 1] = (byte)((c & 0xFF0000) >> 16);
array[j * 4 + 2] = (byte)((c & 0xFF00) >> 8);
array[j * 4 + 3] = (byte)(c & 0xFF);
}
return array;
}
public static int[] convertToIntArray(final byte[] pByteArray)
{
final int[] array = new int[pByteArray.length / 4];
for (int i = 0; i < array.length; i++)
array[i] = (((int)(pByteArray[i * 4]) << 24) & 0xFF000000) |
(((int)(pByteArray[i * 4 + 1]) << 16) & 0xFF0000) |
(((int)(pByteArray[i * 4 + 2]) << 8) & 0xFF00) |
((int)(pByteArray[i * 4 + 3]) & 0xFF);
return array;
}
注意,由于符号传播等原因,在转换回int时需要“& 0xFF…”。