import junit.framework.TestCase;
/**
* 编码与解码测试
* @author jzj
*/
public class TestEncodeDecode extends TestCase {
private char chineseChar = '中';
private char englishChar = 'a';
/**
* Java程序中的字符都是占用二个字节,因为 char 类型好比双字节的无符号整数
*/
public void testCharToUnicode() {
//十进制Uncode编码
System.out.println((int) chineseChar);//20013
System.out.println((int) englishChar);//97
//十六进制Uncode编码
System.out
.println(Integer.toHexString((int) chineseChar).toUpperCase());//4E2D
System.out
.println(Integer.toHexString((int) englishChar).toUpperCase());//61
//二进制Uncode编码
System.out.println(Integer.toBinaryString((int) chineseChar));//100111000101101
System.out.println(Integer.toBinaryString((int) englishChar));//1100001
}
/**
* 不管是中文还是英文都还是其他字符,每个字符都是占用两个字节,虽然英文字符的
* UTF-16编码与Unicode编码是一样的,只不过UTF-16在编码时会在码流前加上"FE FF"两个字节的内容,
* 表示字符是以UTF-16格式存储的,在读取时程序就会知道是UTF-16编码的字符
*/
public void testCharToUTF16() {
try {
//--中文字符转UTF-16
byte[] encodeArr = String.valueOf(chineseChar).getBytes("UTF-16");
//十进制编码输出
for (int i = 0; i < encodeArr.length; i++) {
//-2 -1 78 45
System.out.print(encodeArr[i] + " ");
}
System.out.println();
//十六进制编码输出
for (int i = 0; i < encodeArr.length; i++) {
//FE FF 4E 2D
System.out.print(byteToHex(encodeArr[i]) + " ");
}
System.out.println();
//所占字节数
System.out.println(encodeArr.length - 2);//2
//--英文字符转UTF-16
encodeArr = String.valueOf(englishChar).getBytes("UTF-16");
//十进制编码输出
for (int i = 0; i < encodeArr.length; i++) {
//-2 -1 0 97
System.out.print(encodeArr[i] + " ");
}
System.out.println();
//十六进制编码输出
for (int i = 0; i < encodeArr.length; i++) {
//FE FF 00 61
System.out.print(byteToHex(encodeArr[i]) + " ");
}
System.out.println();
//所占字节数
System.out.println(encodeArr.length - 2);//2
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
责任编辑:小草