計算機中編碼轉換

代碼1

public class BytesCodeTest {編碼

public static void main(String[] args) {
	String test = "安徽省zx";
	System.out.print("原始字符:");
	for (char b : test.toCharArray()) {
		System.out.print(b + " ");
	}
	System.out.println();

	try {
		byte[] iso8859 = test.getBytes("ISO-8859-1");
		printByte("ISO-8859-1", iso8859);

		byte[] gb2312 = test.getBytes("GB2312");
		printByte("GB2312", gb2312);

		byte[] gbk = test.getBytes("GBK");
		printByte("GBK", gbk);

		byte[] utf8 = test.getBytes("UTF-8");
		printByte("UTF-8", utf8);

		byte[] utf16 = test.getBytes("UTF-16");
		printByte("UTF-16", utf16);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

public static void printByte(String charset, byte[] bytes) {
	System.out.print("編碼格式【" + charset + "]時  bytes= ");
	for (byte b : bytes) {
		System.out.print(b + " ");
	}
	System.out.println();
}

}code

程序運行結果:圖片

輸入圖片說明

結論:get

  1. 一、英文字母在以上編碼格式中均是一個byte,且對應的byte值均相同;
  2. 二、ISO-8859-1的編碼格式中一個字符一個byte;
  3. 三、GBK和GB2312的編碼結果基本上相同;
  4. 四、UTF-8編碼格式中一箇中文字符爲三個byte,英文字符是一個byte;
  5. 五、UTF-16編碼格式中每一個字符均是2個byte。******
這裏輸入代碼
```public class BytesCodeTranslate {
	public static void main(String[] args) throws UnsupportedEncodingException {
		String strGBK = "訂單號重複";
		System.out.print("編碼格式爲【GBK】下的bytes: ");
		for (byte bt : strGBK.getBytes("GBK")) {
			System.out.print(bt + " ");
		}
		System.out.println();
		System.out.print("編碼格式爲【UTF-8】下的bytes: ");
		String strUTF8 = new String(strGBK.getBytes("UTF-8"), "UTF-8");
		for (byte bt : strUTF8.getBytes("UTF-8")) {
			System.out.print(bt + " ");
		}
		System.out.println();
		System.out.println("GBK-->UTF-8" + strUTF8);
		System.out.println("UTF-8-->GBK" + new String(strUTF8.getBytes("GBK"), "GBK"));
	}
}
相關文章
相關標籤/搜索