您的位置:首页 > 其它

convert a byte array to a hexadecimal string

2015-04-07 18:34 411 查看
public static String ByteArrayToHexString(byte[] bytes) {
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

// Each byte has two hex characters (nibbles)
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
// Cast bytes[j] to int, treating as unsigned value
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}


或者

/**
* 二进制转十六进制
* 因为一个byte对应8位二进制,取值范围是-128~127
* 所以一个byte对应两个十六进制数字
*
* @param bytes
* @return
*/
public static String bytesToHex(byte[] bytes) {
StringBuffer md5str = new StringBuffer();
//把数组每一字节换成16进制连成md5字符串

int digital;
for (int i = 0; i < bytes.length; i++) {
digital = bytes[i];

if(digital < 0) {
digital += 256;
}
if(digital < 16){
md5str.append("0");
}
md5str.append(Integer.toHexString(digital));
}
return md5str.toString().toUpperCase();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: