如何让字母和汉字合并编码成HEX,HEX解码成字母和汉字
一、什么是Hex
将每一个字节表示的十六进制表示的内容,用字符串来显示。
二、作用
将不可见的,复杂的字节数组数据,转换为可显示的字符串数据
类似于Base64编码算法
区别:Base64将三个字节转换为四个字符,Hex将三个字节转换为六个字节
写这篇博客的原因:???
因为当时组装报文传输要用hex传输,只有Hex可以转换为可视化的字符,但是传输时有字符串还有汉字,这两种格式的编码方式不一样,所以需要重新编码,相反,想要看这个内容一定要解码。
例:把"ascll"这个字符和"编码"这两个汉字需要合并成hex。
ASCLL和GB18030混合编码生成HEX
1.“ascll” 因为是字母,ascll编码就可以搞定,所以字符串用ascll编码就可以。
2."编码"汉字需要用GBK等格式去编码,这里用“GB18030-2000”。
3.两个都要先转成byte。(byte 是没有字符汉字的概念的)
4.然后把转换好的byte转换成HEX。
代码来了
public static void main(String[] args) throws Exception{
String str = "ascll";
String chineseChar = "编码";
byte strByte [] =str.getBytes("ASCII");
byte chineseCharByte [] =chineseChar.getBytes("GB18030-2000");
byte resultByte [] =new byte[strByte.length+chineseCharByte.length];
System.arraycopy(strByte,0,resultByte,0,strByte.length);
System.arraycopy(chineseCharByte,0,resultByte,strByte.length,chineseCharByte.length);
String resultStr = Hex.encodeHexString(resultByte);
System.out.println(resultStr);
}
执行结果:6173636c6cb1e0c2eb
HEX解码成ASCLL和GB18030原字符
1.首先要把HEX字符串转换成byte数组。
2.确定需要解码成ASCLL的byte数组长度。
3.确定需要解码成GB18030-2000的byte数组长度。
4.把总byte数组的数据放到相应的数组byte数组里面。
5.分别进行解码。
代码来了
public static void main(String[] args)throws Exception {
String hexStr = "6173636c6cb1e0c2eb";
byte resultByte [] = EncodeTest.hexStringToBytes(hexStr);
byte strByte [] =new byte[5];
byte chineseCharByte [] =new byte[4];
System.arraycopy(resultByte,0,strByte,0,strByte.length);
System.arraycopy(resultByte,strByte.length,chineseCharByte,0,chineseCharByte.length);
String str = new String(strByte, "ASCII");
String chineseChar = new String(chineseCharByte,"GB18030-2000");
System.out.println(str);
System.out.println(chineseChar);
}
public static byte hexToByte(String inHex){
return (byte)Integer.parseInt(inHex,16);
}
/*
* Convert hex string to byte[]
* @param hexString the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
if(hexString.length()%2!=0){
throw new RuntimeException("Hex bit string length must be even");
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/*
* Convert char to byte
* 'F'-->15
* @param c
* char
* @return byte
*/
private static byte charToByte(char c) {
int index = "0123456789ABCDEF".indexOf(c);
if (index == -1) {
index = "0123456789abcdef".indexOf(c);
}
return (byte) index;
}
执行结果:ascll 编码
编码解码完毕。