閱讀550 返回首頁    go 阿裏雲 go 技術社區[雲棲]


【最近麵試遇到的一些問題】JAVA UTF-8 GB2312 編碼互轉

朋友讓我幫他寫個gb2312->utf-8的字符轉換程序,找了半天沒有在網上找到合適的,於是自己動手寫了一個,嗬嗬。把它貼在這裏,免得以後忘記了 ^_^

    實現思路大致如下:

  •  取得一個漢字的Unicode碼
  • 把Unicode碼分解為兩個16進製數據字符串(丟棄前兩個字節)
  • 把這兩個16進製數據字符串轉換成二進製數據字符串
  • 把二進製數據字符串分解為三個串,第一個串為4(0~4)個位,在高位加上標記位“1110”,第二(4~10)、三個(10~16)串均為6個位,分別在高位加上“10”標記位
  • 把這三個二進製串分別轉換為10進製數據並賦值給字節型數組
  • 根據這個字節型數組構造UTF-8字符
java 代碼
 
  1. import java.io.File;   
  2. import java.io.FileOutputStream;   
  3. import java.io.UnsupportedEncodingException;   
  4.   
  5. /**  
  6.  * 2007-8-10 jyin at gomez dot com  
  7.  */  
  8. public class CharsetConvertor {   
  9.     public static void main(String[] args) {   
  10.         String str = "This is a test for *中網!@#$。,?";   
  11.         try {   
  12.             File f = new File("D:/test.txt");   
  13.             FileOutputStream fio = new FileOutputStream(f);   
  14.             String s = gbToUtf8(str);   
  15.             fio.write(s.getBytes("UTF-8"));   
  16.             fio.close();   
  17.         }   
  18.         catch (Exception e) {   
  19.             e.printStackTrace();   
  20.         }   
  21.     }   
  22.   
  23.     public static String gbToUtf8(String str) throws UnsupportedEncodingException {   
  24.         StringBuffer sb = new StringBuffer();   
  25.         for (int i = 0; i < str.length(); i++) {   
  26.             String s = str.substring(i, i + 1);   
  27.             if (s.charAt(0) > 0x80) {   
  28.                 byte[] bytes = s.getBytes("Unicode");   
  29.                 String binaryStr = "";   
  30.                 for (int j = 2; j < bytes.length; j += 2) {   
  31.                     // the first byte   
  32.                     String hexStr = getHexString(bytes[j + 1]);   
  33.                     String binStr = getBinaryString(Integer.valueOf(hexStr, 16));   
  34.                     binaryStr += binStr;   
  35.                     // the second byte   
  36.                     hexStr = getHexString(bytes[j]);   
  37.                     binStr = getBinaryString(Integer.valueOf(hexStr, 16));   
  38.                     binaryStr += binStr;   
  39.                 }   
  40.                 // convert unicode to utf-8   
  41.                 String s1 = "1110" + binaryStr.substring(04);   
  42.                 String s2 = "10" + binaryStr.substring(410);   
  43.                 String s3 = "10" + binaryStr.substring(1016);   
  44.                 byte[] bs = new byte[3];   
  45.                 bs[0] = Integer.valueOf(s1, 2).byteValue();   
  46.                 bs[1] = Integer.valueOf(s2, 2).byteValue();   
  47.                 bs[2] = Integer.valueOf(s3, 2).byteValue();   
  48.                 String ss = new String(bs, "UTF-8");   
  49.                 sb.append(ss);   
  50.             } else {   
  51.                 sb.append(s);   
  52.             }   
  53.         }   
  54.         return sb.toString();   
  55.     }   
  56.   
  57.     private static String getHexString(byte b) {   
  58.         String hexStr = Integer.toHexString(b);   
  59.         int m = hexStr.length();   
  60.         if (m < 2) {   
  61.             hexStr = "0" + hexStr;   
  62.         } else {   
  63.             hexStr = hexStr.substring(m - 2);   
  64.         }   
  65.         return hexStr;   
  66.     }   
  67.   
  68.     private static String getBinaryString(int i) {   
  69.         String binaryStr = Integer.toBinaryString(i);   
  70.         int length = binaryStr.length();   
  71.         for (int l = 0; l < 8 - length; l++) {   
  72.             binaryStr = "0" + binaryStr;   
  73.         }   
  74.         return binaryStr;   
  75.     }   
  76. }  



另外:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class UnicodeChange {

	//UTF-8->GB2312
	public static String utf8Togb2312(String str){ 

        StringBuffer sb = new StringBuffer(); 

        for ( int i=0; i<str.length(); i++) { 

            char c = str.charAt(i); 
            switch (c) { 
               case '+' : 
                   sb.append( ' ' ); 
               break ; 
               case '%' : 
                   try { 
                        sb.append(( char )Integer.parseInt ( 
                        str.substring(i+1,i+3),16)); 
                   } 
                   catch (NumberFormatException e) { 
                       throw new IllegalArgumentException(); 
                  } 

                  i += 2; 

                  break ; 
                  
               default : 

                  sb.append(c); 

                  break ; 

             } 

        } 

        String result = sb.toString(); 

        String res= null ; 

        try { 

             byte [] inputBytes = result.getBytes( "8859_1" ); 

            res= new String(inputBytes, "UTF-8" ); 

        } 

        catch (Exception e){} 

        return res; 

  }


	//GB2312->UTF-8
	public static String gb2312ToUtf8(String str) { 

        String urlEncode = "" ; 

        try { 

            urlEncode = URLEncoder.encode (str, "UTF-8" ); 

        } catch (UnsupportedEncodingException e) { 

            e.printStackTrace(); 

        } 

        return urlEncode; 

    }
	

	public static void main(String[] args){   
	       	        
	    	try {
			
	    	String str="輸入簡體字,點下麵繁體字按鈕進行在線轉換.";//%E4%B8%AD%E5%9B%BD
	    		
	    	str=gb2312ToUtf8(str);
	    		
			System.out.println(str);
				  
			str=utf8Togb2312(str);
				
			System.out.println(str);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	        
	    }   
	


}


最後更新:2017-04-04 07:03:27

  上一篇:go 編程珠璣之1.2位邏輯運算實現位向量
  下一篇:go POJ 3219 二項式係數奇偶性的判定