我们知道,在java中,一个byte 就是一个字节,也就是八个二进制位;而4个二进制位就可以表示一个十六进制位,所以一个byte可以转化为2个十六进制位。
方式一:

// 把byte 转化为两位十六进制数
public static string tohex(byte b) {
string result = integer.tohexstring(b & 0xff);
if (result.length() == 1) {
result = '0' + result;
}
return result;
}
@test
public void testhex4(){
byte b='a';
system.out.println(tohex(b));
运行结果为 61
方式二:

private static char[] hexcode = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* byte2hexstring
*
* @param b
* @return
*/
public static string byte2hexstring(byte b) {
stringbuffer buffer = new stringbuffer();
buffer.append(hexcode[(b >>> 4) & 0x0f]);
buffer.append(hexcode[b & 0x0f]);
return buffer.tostring();
总结如下:
(1)一个byte 对应两位十六进制位,而不是八位(32位二进制位);
(2)转化为十六进制之后,不足两位的,高位要补零。