方法一
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