一、字节数组转化为十六进制的字符串。
用两位的十六进制数即可表示一个八位的byte数。
第一位十六进制数由byte数向右移动4位(即除于16取模)。第二位十六进制数
直接取byte数的低四位。代码如下
public static String byte2HexString(byte[] b){
StringBuilder buff = new StringBuilder();
for(int i = 0 ; i < b.length;i++){
buff.append([b[i]>>>4])
.append(hex[bi]&0xF);
}
return buff.toString();
}
二、十六进制的字符串表示转化为其他基本数字类型
直接用java常用类中各种基本类型的对象的parse方法
比如, Integer的parseInt(String s, int radix)方法 。
s为要解析的字符串,radix为解析的基数。radix可以任意指定。
将字符串s ="abcd"转化为int型则为:int i= Integer.parseInt(s,16);
其他基本类型与转化为int类型相同。
一个完整的代码如下:
//16进制字符数组
private static char[] hex = new char[] {
'0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static String byte2HexString(byte[] b) {
if (b == null)
return "null";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++) {
sb.append(hex[b[i] >>> 4]).append(hex[b[i] & 0xF]);
}
return sb.toString();
}