byte[]转hex的方法

方法一

    byte[] bytes = {-1, 0, 1, 2, 3 };
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        sb.append(String.format("%02X ", b));
    }
    System.out.println(sb.toString());
    // prints "FF 00 01 02 03 "

说明:
1、java.util.Formatter syntax

%[flags][width]conversion
Flag '0' - The result will be zero-padded,空位用0填充
Width 2 宽度是2
Conversion 'X' - The result is formatted as a hexadecimal integer, uppercase

2、-1是以补码的形式存在的,8位二进制表示11111111。正数的原码、反码、补码全部相同。负数的反码是符号位不变,其余一次取反,补码是反码+1。如:
[+1] = [00000001]原 = [00000001]反 = [00000001]补
[-1] = [10000001]原 = [11111110]反 = [11111111]补

方法二:
uses Integer.toHexString(int); this is doable, but with some caveats. Since the parameter is an int, a widening primitive conversion is performed to the byte argument, which involves sign extension.

    byte b = -1;
    System.out.println(Integer.toHexString(b));
    // prints "ffffffff"

The 8-bit byte, which is signed in Java, is sign-extended to a 32-bit int(4 bytes in java). To effectively undo this sign extension, one can mask the byte with 0xFF.

    byte b = -1;
    System.out.println(Integer.toHexString(b & 0xFF));
    // prints "ff"

Another issue with using toHexString is that it doesn’t pad with zeroes:

    byte b = 10;
    System.out.println(Integer.toHexString(b & 0xFF));
    // prints "a"

补充:
byte to int,补位的方式,如果是正数,则前24位补0,如果是负数,则前24位补1。
int to byte,如果直接强转,则直接丢弃前24位。

        byte a = 40;//8bit 00101000
        byte b = -40;//8bit 10100000
        int c = 129;
        byte d = (byte)c;
        System.out.println("40:" + Integer.toBinaryString((int)a));
        //print 00000000 00000000 00000000 00101000
        System.out.println("-40:" + Integer.toBinaryString((int)b));
        //print 11111111 11111111 11111111 11011000
        System.out.println("c:" + Integer.toBinaryString(c));
        //print c:10000001
        System.out.println("d:" + Integer.toBinaryString(d));
        //print d:11111111111111111111111110000001
        System.out.println("c:" + c);
        //print c:129
        System.out.println("d:" + d);
        //print d:-127
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值