1. byte[]数组转hex
private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String bytesToHex(byte[] bytes) {
// 一个byte为8位,可用两个十六进制位标识
char[] buf = new char[bytes.length * 2];
int a = 0;
int index = 0;
for(byte b : bytes) { // 使用除与取余进行转换
if(b < 0) {
a = 256 + b;
} else {
a = b;
}
buf[index++] = HEX_CHAR[a / 16];
buf[index++] = HEX_CHAR[a % 16];
}
return new String(buf);
}
2. hex转byte[]数组
public static byte[] hexStrToByteArray(String str)
{
if (str == null) {
return null;
}
if (str.length() == 0) {
return new byte[0];
}
byte[] byteArray = new byte[str.length() / 2];
for (int i = 0; i < byteArray.length; i++){
String subStr = str.substring(2 * i, 2 * i + 2);
byteArray[i] = ((byte)Integer.parseInt(subStr, 16));
}
return byteArray;
}
注意:本文归作者所有,未经作者允许,不得转载
原文地址: http://blog.wsmee.com/post/132
版权声明:非商用-非衍生-保持署名| Creative Commons BY-NC-ND 3.0