类型的隐式转换在编码中需要特别的注意。今天遇到了一个bug
- 先做下测试
@Test
public void inttolongValue() {
int tmp = 0x80000000;
long value = (long)tmp;
System.out.println(value);
}
输出结果:-2147483648
* 这里 longToByteArray 的参数从int转为为了long,16进制输出内容,查看转换后每个字节具体内容
public void inttolong() {
System.out.println("0x80000000 , int : " + ByteBufUtil.hexDump(intToByteArray(0x80000000)));
System.out.println("0x80000000 convert to long: " + ByteBufUtil.hexDump(longToByteArray(0x80000000)));
}
public static byte[] longToByteArray(long i) {
byte[] result = new byte[8];
//由高位到低位
result[0] = (byte)((i >> 56) & 0xFF);
result[1] = (byte)((i >> 48) & 0xFF);
result[2] = (byte)((i >> 42) & 0xFF);
result[3] = (byte)((i >> 32) & 0xFF);
result[4] = (byte)((i >> 24) & 0xFF);
result[5] = (byte)((i >> 16) & 0xFF);
result[6] = (byte)((i >> 8) & 0xFF);
result[7] = (byte)(i & 0xFF);
return result;
}
运行结果:
0x80000000 , int : 80000000
0x80000000 convert to long: ffffffff80000000
这里int 转为为long 后,高位全部补充为1,导致了问题