你把每个byte当成int,可以用Integer里的toHexString做到

解决方案 »

  1.   

    DragonAbroad的问题跟中文没有关系。
      

  2.   

    谢谢以上各位;我测试了一下,由String转成hex成功了,可以由hex转成String出了问题:
    代码1:
    public class test {
    public static void main(String[] arg) {
    String s=new String("ABCDEFGHIJKL");
    String ns="";
    byte[] os=new byte[100]; byte[] b=s.getBytes();
    for(int i=0;i<b.length;i++) {
    ns+=Integer.toHexString(new Byte(b[i]).intValue());
    }
    System.out.println(ns);
    System.out.println("------------------------------------------------"); byte[] bb=ns.getBytes();
    byte[] bbb=new byte[2];
    for(int i=0,j=0;i<ns.length();i+=2,j++) {
    bbb[0]=bb[i];
    bbb[1]=bb[i+1];
    // os+=(byte)Integer.parseInt(new String(bbb));
    os[j]=(byte)Integer.parseInt(new String(bbb));
    }
    System.out.println(new String(os));
    }
    }
    编译通过,执行报错:NumberFormatException: 4a代码2:
    public class test {
    public static void main(String[] arg) {
    String s=new String("ABCDEFGHIJKL");
    String ns="";
    String os=""; byte[] b=s.getBytes();
    for(int i=0;i<b.length;i++) {
    ns+=Integer.toHexString(new Byte(b[i]).intValue());
    }
    System.out.println(ns);
    System.out.println("------------------------------------------------"); byte[] bb=ns.getBytes();
    byte[] bbb=new byte[2];
    for(int i=0,j=0;i<ns.length();i+=2,j++) {
    bbb[0]=bb[i];
    bbb[1]=bb[i+1];
    os+=(char)Integer.parseInt(new String(bbb));
    // os[j]=(byte)Integer.parseInt(new String(bbb));
    }
    System.out.println(new String(os));
    }
    }
    编译通过,执行同样报:NumberFormatException: 4a
    为什么会这样????
      

  3.   

    上面的错误我知道了,不能直接用parseInt转换hex值。
    那么该如何转换呢?
      

  4.   

    public static final String toHex (byte hash[]) {
            StringBuffer buf = new StringBuffer(hash.length * 2);
            int i;        for (i = 0; i < hash.length; i++) {
                if (((int) hash[i] & 0xff) < 0x10) {
                    buf.append("0");
                }
                buf.append(Long.toString((int) hash[i] & 0xff, 16));
            }
            return buf.toString();
        }
      

  5.   

    Integer.parseInt("aa", 16);//16表示十六进制