searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

java中int转long的注意事项

2024-11-07 09:25:12
5
0

      类型的隐式转换在编码中需要特别的注意。今天遇到了一个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,导致了问题

0条评论
作者已关闭评论
luyu2
6文章数
0粉丝数
luyu2
6 文章 | 0 粉丝
原创

java中int转long的注意事项

2024-11-07 09:25:12
5
0

      类型的隐式转换在编码中需要特别的注意。今天遇到了一个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,导致了问题

文章来自个人专栏
文章 | 订阅
0条评论
作者已关闭评论
作者已关闭评论
0
0