我們知道,在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)轉化為十六進制之後,不足兩位的,高位要補零。