GB2312中一個漢字是16位,而UTF-8中一個漢字是24位,將UTF-8 轉換成GB2312
java
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: break; } } String result = sb.toString(); String res = null; try{ byte[] inputBytes = result.getBytes("UTF-8"); res = new String(inputBytes,"GB2312"); } catch(Exception e){ e.printStack(); } return res; }