现在的位置: 首页 > 综合 > 正文

java gbk–utf-8乱码解决函数

2013年09月08日 ⁄ 综合 ⁄ 共 726字 ⁄ 字号 评论关闭

public static String gbk2Utf(String gbk) throws UnsupportedEncodingException {
char[] c = gbk.toCharArray();
byte[] fullByte = new byte[3*c.length];
for (int i=0; i<c.length; i++) {
String binary = Integer.toBinaryString(c[i]);
StringBuffer sb = new StringBuffer();
int len = 16 - binary.length();
//前面补零
for(int j=0; j<len; j++){
    sb.append("0");
    }
sb.append(binary);
//增加位,达到到24位3个字节
sb.insert(0, "1110");
       
sb.insert(8, "10");
       
sb.insert(16, "10");
      fullByte[i*3] = Integer.valueOf(sb.substring(0, 8), 2).byteValue();//二进制字符串创建整型
       
fullByte[i*3+1] = Integer.valueOf(sb.substring(8, 16), 2).byteValue();
       
fullByte[i*3+2] = Integer.valueOf(sb.substring(16, 24), 2).byteValue();
}
//模拟UTF-8编码的网站显示
System.out.println(new String(fullByte,"UTF-8"));
return new String(fullByte,"UTF-8");
}

抱歉!评论已关闭.