一、十六进制字符串与byte数组之间的转换
直接展示代码
import java.util.Arrays;
/**
* 十六进制字符串与byte数组之间的转换
* */
public class Hex2BytesUtils {
private static final String HEX_CHARSET = "0123456789ABCDEF";
private static final String BLANK = " ";
/**
* byte数组转换成16进制字符串
* */
public static String byte2HexWithBlank(byte[] b)
{
if ((b == null) || (b.length == 0)) {
return null;
}
StringBuilder sb = new StringBuilder(b.length * 3);
int size = b.length;
for (int n = 0; n < size; n++) {
sb.append("0123456789ABCDEF".charAt(0xF & b[n] >> 4)).append("0123456789ABCDEF".charAt(b[n] & 0xF)).append(" ");
}
return sb.toString();
}
/**
* 16进制字符串转换成byte数组
* */
public static byte[] Hex2Bytes(String hexString){
byte[] arrB = hexString.getBytes();
int iLen = arrB.length;
byte[] arrOut = new byte[iLen / 2];
String strTmp = null;
for (int i = 0; i < iLen; i += 2)
{
strTmp = new String(arrB, i, 2);
arrOut[(i / 2)] = ((byte)Integer.parseInt(strTmp, 16));
}
return arrOut;
}
public static void main(String[] args) {
//byte数组转成16进制字符串
String str = "抗美援朝70周年";
byte[] strByte = str.getBytes();
System.out.println("抗美援朝70周年 转化成byte数组为:"+Arrays.toString(strByte));
String StrHex = byte2HexWithBlank(strByte);
System.out.println("抗美援朝70周年 转化成16进制字符串为:"+StrHex);
System.out.println("===================================================");
//16进制字符串转换成byte数组
String strHex1 ="E68A97E7BE8EE68FB4E69C9D3730E591A8E5B9B4";
byte[] hexbyte = Hex2Bytes(strHex1);
System.out.println("E68A97E7BE8EE68FB4E69C9D3730E591A8E5B9B4 转换成byte数组为:" + Arrays.toString(hexbyte));
System.out.println("E68A97E7BE8EE68FB4E69C9D3730E591A8E5B9B4 转换成字符串为:" + new String(hexbyte));
}
}
//运行结果如下所示:
抗美援朝70周年 转化成byte数组为:[-26, -118, -105, -25, -66, -114, -26, -113, -76, -26, -100, -99, 55, 48, -27, -111, -88, -27, -71, -76]
抗美援朝70周年 转化成16进制字符串为:E6 8A 97 E7 BE 8E E6 8F B4 E6 9C 9D 37 30 E5 91 A8 E5 B9 B4
===================================================
E68A97E7BE8EE68FB4E69C9D3730E591A8E5B9B4 转换成byte数组为:[-26, -118, -105, -25, -66, -114, -26, -113, -76, -26, -100, -99, 55, 48, -27, -111, -88, -27, -71, -76]
E68A97E7BE8EE68FB4E69C9D3730E591A8E5B9B4 转换成字符串为:抗美援朝70周年