byte到16进制转换

我有一个字节数组。我希望将该数组的每个字节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.

你可能感兴趣的:(java,byte,java)