比如:人 这个汉字,它的UTF-8编码为:E4 BA BA ,那么我怎么把这几个字符,转换成:"人"这个汉字呢.大家帮帮我吧.

解决方案 »

  1.   

    String utf;
    ...
    String gbk=new String(utf.getBytes("utf-8"),"gb2312");
      

  2.   

    写了三种不同的方法,楼主可以参考一下:import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;public class Test {  public static void main(String[] args) throws UnsupportedEncodingException {    String str = "40 D0 BF E4 BA BA 35";    // 方法一:采用 URLDecoder.decode() 转换浏览器地址栏中的方法
        String newStr = URLDecoder.decode("%" + str.replace(" ", "%"), "utf-8");
        System.out.println(newStr);    // 方法二:将字符序列转为 byte 数组
        String[] strs = str.split(" ");
        byte[] b = new byte[strs.length];
        for(int i=0; i<strs.length; i++){
          b[i] = (byte)Integer.parseInt(strs[i], 16);
        }
        newStr = new String(b, "utf-8");
        System.out.println(newStr);
        
        // 方法三:按照 UTF-8 的编码格式,直接解析字符串
        strs = str.split(" ");
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<strs.length; i++){
          int n1 = Integer.parseInt(strs[i], 16);      
          if ( (n1 >> 5) == 0x6 ) {
            int n2 = Integer.parseInt(strs[++i], 16);
            n1 = (n1 & 0x1F) << 6;
            n2 = n2 & 0x3F;
            n1 |= n2;                
          } else if ( (n1 >> 4) == 0xE) {
            int n2 = Integer.parseInt(strs[++i], 16);
            int n3 = Integer.parseInt(strs[++i], 16);
            n1 = (n1 & 0x0F) << 12;
            n2 = (n2 & 0x3F) << 6;
            n3 = (n3 & 0x3F);
            n1 = n1 | n2 | n3;
          }
          sb.append((char)n1);
        }
        System.out.println(sb.toString());
      }
    }