Integer.toHexString的代码片段:
final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
//十六进制
public static String toHexString(int i){
char[] buf = new char[32];
int charPos = 32;
do {
buf[--charPos] = digits[i & 0xf];
i >>>= 4;
} while (i != 0);
System.out.println(charPos);
return new String(buf, charPos, (32 - charPos));
}
//二进制
public static String toBinaryString(int i){
char[] buf = new char[32];
int charPos = 32;
do{
buf[--charPos] = digits[i &0x1];
i>>>=1;
}while(i!=0);
return new String(buf,charPos,32-charPos);
}
其核心就是将低4位与0xf进行与运算,得到其十六进制的字符,然后右移4位,如此循环,得到其十六进制编码的字符串。
需要注意的是,int类型是32位,byte是8位的。如果一个byte变量是负数,计算机中是以补码存储的,比如byte n=-1,其十六进制补码为0xff,在调用toHexString(int i)时,传递的参数被强制转换成32位的int类型,它这时的补码为0xffff ffff。
所以byte类型变量显示其十六进制编码时要先和0xff进行一下与运算,去掉溢出部分:Integer.toHexString(byte & 0xff)。