下面代码是根据该博客:http://gufenglian.iteye.com/blog/348282,进行了完善后得出的。
public class TestUTF8 {
public static void main(String... args) {
//下面打印出所有的中文字符串
long start= 0x4E00;
long end = 0x9FA5;
do {
System.out.println(toStringHex(Long.toHexString(start)));
start++;
} while (start < end);
}
public static String toHexString(String s){
String str="";
for (int i=0;i<s.length();i++){
int ch = (int)s.charAt(i);
String s4 = Integer.toHexString(ch);
if(s4.length()<4)
/*
* 当此处是[a-zA-Z0-9]等ascii值时,
* 获得的16进制字符串长度小于4,
* 如果不加上"00",
* 在传入的字符串中即包含中文,又包含英文时,
* 调用下面方法toStringHex无法得出正确的结果。
*/
s4="00"+s4;
str = str + s4;
}
System.out.println(str);
return str;
}
/**
* 转化十六进制编码为字符串
*/
public static String toStringHex(String s){
byte[] baKeyword = new byte[s.length()/2];
for(int i = 0; i < baKeyword.length; i++){
try{
baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16));
}catch(Exception e){
e.printStackTrace();
}
}
try{
//中文占用了2个字节,此处必须用“utf-16”,否则无法正确获取中文字符
s = new String(baKeyword, "utf-16");//UTF-16le:Not
}catch (Exception e1){
e1.printStackTrace();
}
return s;
}
}
本文提供了一个Java程序示例,演示如何将UTF-8编码的中文字符转换为UTF-16编码。通过遍历Unicode范围内所有中文字符,并将其从UTF-8转换为UTF-16进行打印,此程序有助于理解不同字符集间的转换过程。
1万+

被折叠的 条评论
为什么被折叠?



