我这里想把一个十六进制数转为字符串,可是乱码了,请大家帮忙解决一下,代码如下,我在网上找了很多都发现和他们的一样,但是我这里就是乱码,返回的“���”,唉~
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();
}
}
}

解决方案 »

  1.   

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

  2.   


    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();
    }
    UTF-8编码对ASCII字符还是按一个字节来表示,对中文或者其它字符可能是2,3,4个字节来表示.要想理解就去看UTF-8规范
      

  3.   


    //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();
            }
        }
      

  4.   

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

  5.   

    /**
     * 字符串转换成十六进制值
     */
    public static String bin2hex(String bin) throws Exception {
    byte[] bs =  bin.getBytes(); 
    StringBuilder sb = new StringBuilder(bs.length*2);
    for(int   i=0;i <bs.length;i++) 

    sb.append(hexString.charAt((bs[i]&0xf0)>>4)); 
    sb.append(hexString.charAt((bs[i]&0x0f)>>0)); 

    return sb.toString();
    }