Java 字节数组类型(byte[])与int类型互转方法
发布时间:2023-05-16 10:05:06
Java中byte[]和int类型是两种不同的数据类型,不能直接转换。但有时候我们需要把byte[]类型转换成int类型或者把int类型转换成byte[]类型,比如在网络传输中序列化和反序列化数据时就需要进行这样的转换。
下面介绍几种byte[]和int类型互转的方法。
1. byte[]转int
byte[]转int需要考虑字节序(Big-endian或Little-endian),因为字节序对转换结果有影响。以下是两种方法。
1.1 使用ByteBuffer
使用ByteBuffer类可以在转换时指定字节序:
public static int byteArrayToInt(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.order(ByteOrder.LITTLE_ENDIAN);
return buffer.getInt();
}
这里设置字节序为Little-endian,即从低位开始读取字节。如果byte[]里的字节序为Big-endian,需要改成:
buffer.order(ByteOrder.BIG_ENDIAN);
1.2 手动转换
手动转换需要注意字节序,以下代码展示如何把byte[]转换成int并指定字节序为Big-endian:
public static int byteArrayToInt(byte[] bytes) {
int result = (bytes[0] << 24)
+ ((bytes[1] & 0xFF) << 16)
+ ((bytes[2] & 0xFF) << 8)
+ (bytes[3] & 0xFF);
return result;
}
如果需要Little-endian,需要改成:
public static int byteArrayToInt(byte[] bytes) {
int result = (bytes[3] << 24)
+ ((bytes[2] & 0xFF) << 16)
+ ((bytes[1] & 0xFF) << 8)
+ (bytes[0] & 0xFF);
return result;
}
2. int转byte[]
int转byte[]需要指定字节序。以下是两种方法。
2.1 使用ByteBuffer
使用ByteBuffer可以方便地进行int到byte[]的转换,并指定字节序:
public static byte[] intToByteArray(int value) {
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(value);
return buffer.array();
}
这里同样设置字节序为Little-endian,如果需要Big-endian,需要改成:
buffer.order(ByteOrder.BIG_ENDIAN);
2.2 手动转换
手动转换同样需要注意字节序。以下代码展示如何把int转换成byte[]并指定字节序为Big-endian:
public static byte[] intToByteArray(int value) {
byte[] bytes = new byte[4];
bytes[0] = (byte) (value >> 24);
bytes[1] = (byte) (value >> 16);
bytes[2] = (byte) (value >> 8);
bytes[3] = (byte) value;
return bytes;
}
如果需要Little-endian,需要改成:
public static byte[] intToByteArray(int value) {
byte[] bytes = new byte[4];
bytes[3] = (byte) (value >> 24);
bytes[2] = (byte) (value >> 16);
bytes[1] = (byte) (value >> 8);
bytes[0] = (byte) value;
return bytes;
}
以上是四种byte[]和int类型互转的方法。使用时需要根据实际需求选择。
