###byte[] -> int
int result = ByteBuffer.wrap(bytes).getInt();
或者:
public static byte[] intToBytes(int i) {
byte[] targets = new byte[4];
targets[3] = (byte) (i & 0xFF);
targets[2] = (byte) (i >> 8 & 0xFF);
targets[1] = (byte) (i >> 16 & 0xFF);
targets[0] = (byte) (i >> 24 & 0xFF);
return targets;
}
###int -> byte[]
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
或
public static int bytesToInt(byte[] bytes, int off) {
int b0 = bytes[off] & 0xFF;
int b1 = bytes[off + 1] & 0xFF;
int b2 = bytes[off + 2] & 0xFF;
int b3 = bytes[off + 3] & 0xFF;
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}
public static byte[] toByteArray(long value) {
return ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(value).array();
}
public static long byteArrayToLong(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.put(bytes, 0, bytes.length);
buffer.flip();
return buffer.getLong();
}
本文介绍如何在Java中实现byte数组与int类型之间的相互转换。提供了两种byte数组转int的方法,一种利用ByteBuffer,另一种通过位操作实现;同时给出了int转byte数组的两种方式。
1万+

被折叠的 条评论
为什么被折叠?



