java实现汉字转编码

 /** 取得字符串编码后的十六进制串.
     *
     * @param s 字符串.
     * @param charsetName 字符集名称. 如 GBK.
     * @return 返回编码后的十六进制串.
     * @throws UnsupportedEncodingException 如果指定的字符集不受支持.
     */
    public static String strGetBytesHex(String s, String charsetName) throws UnsupportedEncodingException {
     StringBuilder rt = new StringBuilder();
     if (null==s) return null;
     byte[] arr;
     if (null!=charsetName && charsetName.length()>0) {
      arr = s.getBytes(charsetName);
     }
     else {
      arr = s.getBytes();
     }
     if (null==arr) return null;
     for(int i=0; i<arr.length; ++i) {
      String s2 = Integer.toHexString(arr[i] & 0x0FF).toUpperCase();
      if (s2.length()<2) s2="0"+s2;
      rt.append(s2);
     }
     return rt.toString();
    }

猜你喜欢

转载自605277272.iteye.com/blog/2204300