GBK与UTF各种格式转码成unicode(java代码)
注意:因为java项目使用的是unicode,所以在提交代码时,如果配置文件中有中文就很尴尬了很容器出现乱码,所以下面这段代码就将中文转换成unicode
代码:
public void test6() throws UnsupportedEncodingException {
//将中文字符按照GBK编码获取的字节码,在按照ISO8859-1编码成字符串,在获得对应的char字符
char[] utfBytes = new String("网络设备".getBytes("GBK"), "ISO8859-1").toCharArray();
String unicodeBytes = "";
//将字符
for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
System.out.println(utfBytes[byteIndex]);
String hexB = Integer.toHexString(utfBytes[byteIndex]); // ת»»Îª16½øÖÆÕûÐÍ×Ö·û´®
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\\u" + hexB;
}
System.out.println("unicodeBytes is: " + unicodeBytes);
}
解释:
1.Integer.toHexString:这个方法是将十进制的数字转成二进制
2.new String(“网络设备”.getBytes(“GBK”), “ISO8859-1”):GBK是双字节编码中文,以ISO8859-1编码(单字节)
3.GBK兼容ISO8859-1编码,相对于iso8859-1编码来说,uniocode编码只是在前面增加了一个0字节,比如字母a为”00 61”(十六进制是061,表示是16进制)
4.上面的网络设备对应ISO8859-1,8个字节的编码。