日期:2014-05-20  浏览次数:20813 次

十六进制转字符串乱码问题
我这里想把一个十六进制数转为字符串,可是乱码了,请大家帮忙解决一下,代码如下,我在网上找了很多都发现和他们的一样,但是我这里就是乱码,返回的“???”,唉~

Java code

package cn.com.jiayi.test;

public class Test {
    public static void main(String [] args){
        String s = "FFFFFF";
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(
                        i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            System.out.println(s);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}


------解决方案--------------------
按我理解的那样,直接可以这样搞定,
Java code
public class Test {
    public static void main(String [] args){
        String s = "FFFFFF";
//        s="00000F";
        int a=Integer.parseInt(s,16);
        System.out.println(a);
    }
}

------解决方案--------------------
Java code

String s = "3031323334";
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            System.out.println(s);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

------解决方案--------------------
Java code

    //1. byte最大只能存储127
    //2. 汉字需要计算4个byte
    //3. 汉字编码范围从4E00到9FA5
    //4. 写在代码里并且只是在控制台显示的话不需要转码
    
    public static void main(String [] args){
        String s = "62114EEC";
        char[] baKeyword = new char[s.length() / 4];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (char)Integer.parseInt(s.substring(i * 4, i * 4 + 4), 16);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            System.out.println(baKeyword);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

------解决方案--------------------
public class Test {
public static void main(String [] args){
String s = "FFFFFF";
int a=Integer.parseInt(s,16);
System.out.println(a);
}
}