天天看點

編碼解碼亂碼字元集

編碼EnCode:将字元轉化為位元組

解碼DeCode:将位元組轉化為字元

亂碼:打個比方---比較多人知道的聯通 用字元集GBK的時候出現這樣的情況:��ͨ,這就是亂碼

常見的中文字元集有:GBK 和 UTF-8

國際上常用的字元集:Unicode(大字典)、ANSI

UTF-8,中文占三個位元組,英文占一個位元組(變長),還有定長占兩個位元組(耗費空間多)

GBK,中文占兩個zijie

下面模拟編碼:

我的預設的編碼字元集為:

編碼解碼亂碼字元集
import java.io.UnsupportedEncodingException;

/**
 * 編碼:将字元轉化為位元組
 * @author Administrator
 *
 */
public class MyEnCode {
	public static void main(String[] args) throws UnsupportedEncodingException {
		String msg = "性命生命使命a";
		
		//預設字元集編碼,這裡預設為GBK
		byte[] datas = msg.getBytes();
		System.out.println(datas.length);
		
		//使用不同字元集編碼,如UTF-8
		datas = msg.getBytes("UTF-8");
		System.out.println(datas.length);
	}
}
           

 結果顯示:

13
19
           

說明:不同的字元集得到的位元組數是不一樣的

下面模拟解碼的情況:

import java.io.UnsupportedEncodingException;

/**
 * 編碼:将字元轉化為位元組
 * 解碼:将位元組轉化為字元
 * @author Administrator
 *
 */
public class MyDeCode {
	public static void main(String[] args) throws UnsupportedEncodingException {
		String msg = "性命生命使命a";
		//編碼
		byte[] datas = msg.getBytes();
		
		//解碼
		msg = new String(datas,0,datas.length,"GBK");
		System.out.println(msg);
		
		//亂碼:
		//(1)位元組數不夠
		msg = new String(datas,0,datas.length-2,"GBK");
		System.out.println(msg);
		
		msg = new String(datas,0,datas.length-1,"GBK");
		System.out.println(msg);
		
		//(2)沒有使用和預設一樣的字元集
		msg = new String(datas,0,datas.length-1,"UTF-8");
		System.out.println(msg);
	}
}
           

 結果:

性命生命使命a
性命生命使?
性命生命使命
???????????