请教JAVA怎么将十六进制转换为字符串,多谢

如题所述

private static String hexString = "0123456789ABCDEF";
public static void main(String[] args) {
    System.out.println(encode("中文"));
    System.out.println(decode(encode("中文")));
}
/*
 * 将字符串编码成16进制数字,适用于所有字符(包括中文)
 */
public static String encode(String str) {
    // 根据默认编码获取字节数组
    byte[] bytes = str.getBytes();
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    // 将字节数组中每个字节拆解成2位16进制整数
    for (int i = 0; i < bytes.length; i++) {
sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
}
    return sb.toString();
}

/*
 * 将16进制数字解码成字符串,适用于所有字符(包括中文)
 */
public static String decode(String bytes) {
    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());
}
亲测可行,支持中文!!!

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-26
16进制转为10进制字符串
public static void main(String[] args) {
String str = "0123456789ABCDEF";
int data = 0xee; //十六进制数
int scale = 10; //转化目标进制

String s = "";
while(data > 0){
if(data < scale){
s = str.charAt(data) + s;
data = 0;
}else{
int r = data%scale;
s = str.charAt(r) + s;
data  = (data-r)/scale;
}
}

System.out.println(s);

}

相似回答