Java byte 数组与 int long 互转

单个 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;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值