通过redis-cli使用redis做存储时,发现当存入的值为汉字时,实际存入的是汉字对应编码的十六进制串。当时的第一反应是从redis中拿到的是一个十六进制串,我应该对这个十六进制串进行解码,解成汉字。随后试着去写了一个十六进制字符串与String互转的demo。但当我使用jedis取数据时,发现取出来的其实就是解码过后的汉字串,猜测应该是jedis做了解码这一过程,之后的文章我会对此进行讲解,先分享一下这个无用功的demo。
public class EnDecode {
private static final char[] DIGITS_HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index);
}
return digit;
}
/**
* @param: [str] 字符串
* @return: java.lang.String 十六进制串
* @author: zhuoli
* @date: 2018/6/4 12:51
*/
public static String toHex(String str) {
byte[] data = str.getBytes();
int outLength = data.length;
char[] out = new char[outLength << 1];
for (int i = 0, j = 0; i < outLength; i++) {
out[j++] = DIGITS_HEX[(0xF0 & data[i]) >>> 4];
out[j++] = DIGITS_HEX[0x0F & data[i]];
}
return new String(out);
}
/**
* @param: [hex] 十六进制字符串
* @return: java.lang.String String串
* @author: zhuoli
* @date: 2018/6/4 12:48
*/
public static String fromHex(String hex) {
/*兼容带有\x的十六进制串*/
hex = hex.replace("\\x","");
char[] data = hex.toCharArray();
int len = data.length;
if ((len & 0x01) != 0) {
throw new RuntimeException("字符个数应该为偶数");
}
byte[] out = new byte[len >> 1];
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f |= toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return new String(out);
}
public static void main(String[] args) {
String s = "卓立测试";
String hex = toHex(s);
System.out.println("原字符串:" + s);
System.out.println("十六进制字符串:" + hex);
String decode = fromHex("\\xE5\\x8D\\x93\\xE7\\xAB\\x8B\\xE6\\xB5\\x8B\\xE8\\xAF\\x95");
System.out.println("解码:" + decode);
}
}
运行结果:
Connected to the target VM, address: '127.0.0.1:6253', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:6253', transport: 'socket'
原字符串:卓立测试
十六进制字符串:E58D93E7AB8BE6B58BE8AF95
解码:卓立测试
Process finished with exit code 0
如果想通过redis-cli读取原汉字字符串,而不是十六进制串,可以在redis-cli后加上 –raw,如下
redis-cli --raw -h ip -p port