byte到16进制转换

1 篇文章 0 订阅

我有一个字节数组。我希望将该数组的每个字节String转换为其对应的十六进制值。

Java中是否有任何函数可以将字节数组转换为十六进制?

byte:

  • byte 数据类型是8位、有符号的,以二进制补码表示的整数;
  • 最小值是 -128(-2^7);
  • 最大值是 127(2^7-1);
  • 默认值是 0;
  • byte 类型用在大型数组中节约空间,主要代替整数,因为 byte 变量 占用的空间只有 int 类型的四分之一;
  • 例子:byte a = 100,byte b = -50。
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 "

%[flags][width]conversion

  • Flag ‘0’ - The result will be zero-padded
  • Width 2
  • Conversion ‘X’ - The result is formatted as a hexadecimal integer, uppercase

Looking at the text of the question, it’s also possible that this is what is requested:

String[] arr = {"-1", "0", "10", "20" };
for (int i = 0; i < arr.length; i++) {
    arr[i] = String.format("%02x", Byte.parseByte(arr[i]));
}
System.out.println(java.util.Arrays.toString(arr));
// prints "[ff, 00, 0a, 14]"

Several answers here 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. 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"

Both factors combined should make the String.format solution more preferrable.

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值