单个 byte 直接转换为 int long 会有符号问题,可和 0xFF 与运算解决。
另外一种方法是利用 ByteBuffer 类。
public static void intToByteArray(int intValue, byte[] bytes) {
bytes[0] = (byte) ((intValue >> 24) & 0xFF);
bytes[1] = (byte) ((intValue >> 16) & 0xFF);
bytes[2] = (byte) ((intValue >> 8) & 0xFF);
bytes[3] = (byte) (intValue & 0xFF);
}
public static int byteArrayToInt(byte[] bytes) {
return byteArrayToInt(bytes, 0);
}
public static int byteArrayToInt(byte[] bytes, int offset) {
return (bytes[offset] & 0xFF) << 24
| (bytes[offset + 1] & 0xFF) << 16
| (bytes[offset + 2] & 0xFF) << 8
| bytes[offset + 3] & 0xFF;
}
public static void longToByteArray(long longValue, byte[] bytes) {
bytes[0] = (byte) ((longValue >> 56) & 0xFF);
bytes[1] = (byte) ((longValue >> 48) & 0xFF);
bytes[2] = (byte) ((longValue >> 40) & 0xFF);
bytes[3] = (byte) ((longValue >> 32) & 0xFF);
bytes[4] = (byte) ((longValue >> 24) & 0xFF);
bytes[5] = (byte) ((longValue >> 16) & 0xFF);
bytes[6] = (byte) ((longValue >> 8) & 0xFF);
bytes[7] = (byte) (longValue & 0xFF);
}
public static long byteArrayToLong(byte[] bytes) {
return byteArrayToLong(bytes, 0);
}
public static long byteArrayToLong(byte[] bytes, int offset) {
return ((long) bytes[offset] & 0xFF) << 56
| ((long) bytes[offset + 1] & 0xFF) << 48
| ((long) bytes[offset + 2] & 0xFF) << 40
| ((long) bytes[offset + 3] & 0xFF) << 32
| ((long) bytes[offset + 4] & 0xFF) << 24
| ((long) bytes[offset + 5] & 0xFF) << 16
| ((long) bytes[offset + 6] & 0xFF) << 8
| (long) bytes[offset + 7] & 0xFF;
}
本文介绍Java中如何将单个byte转换为int或long类型,避免符号问题,并提供int、long与byte数组相互转换的方法。通过位操作和掩码运算实现高效的数据类型转换。
4万+

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



