读书人

字符串 与16进制字符串互相转换

发布时间: 2012-12-20 09:53:21 作者: rapoo

字符串 与16进制字符串相互转换

下面代码是根据该博客:http://gufenglian.iteye.com/blog/348282,进行了完善后得出的。

public class TestUTF8 {    public static void main(String... args) {        //下面打印出所有的中文字符串        long start= 0x4E00;        long end = 0x9FA5;        do {           System.out.println(toStringHex(Long.toHexString(start)));           start++;        } while (start < end);    }        public static String toHexString(String s){            String str="";        for (int i=0;i<s.length();i++){            int ch = (int)s.charAt(i);            String s4 = Integer.toHexString(ch);            if(s4.length()<4)                /*                 * 当此处是[a-zA-Z0-9]等ascii值时,                 * 获得的16进制字符串长度小于4,                 * 如果不加上"00",                 * 在传入的字符串中即包含中文,又包含英文时,                 * 调用下面方法toStringHex无法得出正确的结果。                 */                s4="00"+s4;            str = str + s4;        }        System.out.println(str);        return str;    }         /**     * 转化十六进制编码为字符串     */      public static String toStringHex(String s){        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{            //中文占用了2个字节,此处必须用“utf-16”,否则无法正确获取中文字符            s = new String(baKeyword, "utf-16");//UTF-16le:Not          }catch (Exception e1){              e1.printStackTrace();          }        return s;    }  }
?

?

读书人网 >编程

热点推荐