表达 数字的ascii string 转换回原始的数字
public static final byte[] toHex (byte hash[]) {
byte[] bytes = new byte[hash.length/2];
int i;
int j = 0;
int len = ((int)(hash.length / 2 )) *2;
for (i = 0; i < len; i +=2 ) {
byte a = hash[i];
byte b = hash[i+1];
if(a >= '0' && a <= '9' )
a = (byte) (a - '0');
else
a = (byte)(a - 'A' + 10);
if(b >= '0' && b <= '9' )
b = (byte) (b - '0');
else
b = (byte)(b - 'A' + 10);
bytes[j] = (byte) (a*16 + b);
j++;
}
return bytes;
}
还有一种写法类似这样:
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
但执行 parseInt时候一直出现异常,搞崩溃程序。还是用我的原始转换代码吧,保证不出问题。