ste*_*fan 178 java arrays byte integer
我得到一个整数: 1695609641
当我使用方法时:
String hex = Integer.toHexString(1695609641);
system.out.println(hex);
Run Code Online (Sandbox Code Playgroud)
得到:
6510f329
Run Code Online (Sandbox Code Playgroud)
但我想要一个字节数组:
byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
dfa*_*dfa 281
使用Java NIO的ByteBuffer非常简单:
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
Run Code Online (Sandbox Code Playgroud)
输出:
0x65 0x10 0xf3 0x29
Grz*_*zki 141
怎么样:
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
Run Code Online (Sandbox Code Playgroud)
这个想法不是我的.我是从dzone.com上的一些帖子中得到的.
vmp*_*mpn 43
BigInteger.valueOf(1695609641).toByteArray()
Yur*_*nko 25
byte[] IntToByteArray( int data ) {
byte[] result = new byte[4];
result[0] = (byte) ((data & 0xFF000000) >> 24);
result[1] = (byte) ((data & 0x00FF0000) >> 16);
result[2] = (byte) ((data & 0x0000FF00) >> 8);
result[3] = (byte) ((data & 0x000000FF) >> 0);
return result;
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*sky 21
使用番石榴:
byte[] bytearray = Ints.toByteArray(1695609641);
Run Code Online (Sandbox Code Playgroud)
byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;
Run Code Online (Sandbox Code Playgroud)
小智 6
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;
}
Run Code Online (Sandbox Code Playgroud)