数据类型转换
public static byte[] intTobytes(int num) {
byte[] result = new byte[4];
for (int i = 0; i < 4; i++) {
result[i] = (byte) (num >> (i * 8));
}
return result;
}
/*
*value[i] & 0xFF的原因是:byte类型转换成int类型时,在计算机中以补码形式存在,如果byte是负数,那么其转换成int类型时,其补码形*式的前三个高位字节均是1111 1111 ,在我们的 result |= (value[i] & 0xFF) << (i * 8) 处理中,影响最终结果
*因此,需要与0xFF相与,将其补码形式的前三个高位字节变为0000 0000
*/
public static int bytesToInt(byte[] value) {
int result = 0;
for (int i = 0; i < 4; i++) {
result |= (value[i] & 0xFF) << (i * 8);
}
return result;
}