首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

JAVA兑现GBK转码为UTF-8

2012-10-13 
JAVA实现GBK转码为UTF-8public static String getUTF8StringFromGBKString(String gbkStr) {try {return n

JAVA实现GBK转码为UTF-8

public static String getUTF8StringFromGBKString(String gbkStr) {try {return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");} catch (UnsupportedEncodingException e) {throw new InternalError();}}


public static byte[] getUTF8BytesFromGBKString(String gbkStr) {int n = gbkStr.length();byte[] utfBytes = new byte[3 * n];int k = 0;for (int i = 0; i < n; i++) {int m = gbkStr.charAt(i);if (m < 128 && m >= 0) {utfBytes[k++] = (byte) m;continue;}utfBytes[k++] = (byte) (0xe0 | (m >> 12));utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));utfBytes[k++] = (byte) (0x80 | (m & 0x3f));}if (k < utfBytes.length) {byte[] tmp = new byte[k];System.arraycopy(utfBytes, 0, tmp, 0, k);return tmp;}return utfBytes;}

热点排行