编码表

编码表的由来:

  计算机只能识别二进制数据,早期由来是电信号

  为了方便应用计算机,让他可以识别各个国家的文字

  就将各个国家的文字用数字来表示,并一一对应,形成一张表,这就是编码表

 

常见编码表:

  ASCII:美国标准信息交换码。用一个字节的7位可以表示

    ISO8859-1:拉丁码表。欧洲码表,用一个字节的8位表示

  GB2312:中国的中文编码表

  GBK:中国的中文编码表升级,融合了更多的中文文字符号

  Unicode:国际标准码,融合了多种文字。所有文字都用两个字节来表示,java语言使用的就是Unicode

  UTF-8:最多用三个字节来表示一个字符

import java.io.IOException;
import java.io.UnsupportedEncodingException;
/*
 * 字符串 --> 字节数组:编码。
 * 字节数组 --> 字符串:解码。
 * 
 * 你好:GBK:  -60 -29 -70 -61
 * 
 * 你好: utf-8: -28 -67 -96 -27 -91 -67 
 * 
 * 
 * 如果你编错了,解不出来。
 * 如果编对了,解错了,有可能有救。
 */
public class Test {
    public static void main(String[] args) throws IOException {
        String str = "谢谢";
        
        byte[] buf = str.getBytes("gbk");
        
        String s1 = new String(buf,"gbk");
        
        System.out.println("s1="+s1);
        
        
        byte[] buf2 = s1.getBytes("UTF-8");//获取源字节.
        
        printBytes(buf2);//-17 -65 -67 -17 -65 -67 -17 -65 -67 
                    //-17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67
                    //-48 -69 -48 -69 
        String s2 = new String(buf2,"GBK");
        
        System.out.println("s2="+s2);
        
        encodeDemo(str);
    }
    public static void encodeDemo(String str)throws UnsupportedEncodingException {
        //编码;
        byte[] buf = str.getBytes("UTF-8");
        
        //printBytes(buf);
        
        //解码:
        String s1 = new String(buf,"UTF-8");
        
        System.out.println("s1="+s1);
    }
    
    private static void printBytes(byte[] buf) {
        for(byte b : buf){
            System.out.print(b +" ");
        }
    }
}

 

posted @ 2014-03-16 14:55  胡椒粉hjf  阅读(366)  评论(0编辑  收藏  举报