java中hex转换成字符串怎么转
1个回答
展开全部
public class Test {
private static String hexString = "0123456789ABCDEFabcdef";
public static void main(String[] args) {
String msg= "亲,你好";
System.out.println(encode(msg));
System.out.println(decode(encode(msg)));
}
public static String encode(String str) {
byte[] bytes = str.getBytes();
StringBuilder sb = new StringBuilder(bytes.length * 2);
//转换hex编码
for (byte b : bytes) {
sb.append(Integer.toHexString(b + 0x800).substring(1));
}
str = sb.toString();
return str;
}
//把hex编码转换为string
public static String decode(String bytes) {
bytes = bytes.toUpperCase();
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
// 将每2位16进制整数组装成一个字节
for (int i = 0; i < bytes.length(); i += 2)
baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
return new String(baos.toByteArray());
}
}
private static String hexString = "0123456789ABCDEFabcdef";
public static void main(String[] args) {
String msg= "亲,你好";
System.out.println(encode(msg));
System.out.println(decode(encode(msg)));
}
public static String encode(String str) {
byte[] bytes = str.getBytes();
StringBuilder sb = new StringBuilder(bytes.length * 2);
//转换hex编码
for (byte b : bytes) {
sb.append(Integer.toHexString(b + 0x800).substring(1));
}
str = sb.toString();
return str;
}
//把hex编码转换为string
public static String decode(String bytes) {
bytes = bytes.toUpperCase();
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
// 将每2位16进制整数组装成一个字节
for (int i = 0; i < bytes.length(); i += 2)
baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
return new String(baos.toByteArray());
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询