UTF-8エンコーディング

2839 ワード

詳細
UTF-8
一、
1.Unicode
A='65'はAsciII表より知られている.すなわち、文字Aを操作する場合、コンピュータ内部でUnicode 65を操作する
2.Java char<=>>Unicode標準文字セット

int a = 'A';
System.out.println(a);
//  int , ,  'A'  A 65

出力結果:65
3.UTF-8は1~4バイトが長くなることを示す
中国語でUTF-8を3バイトにエンコードするのはなぜですか?
3.1漢字のバイナリコードを出力する

Integer b = ' ';
System.out.println(Integer.toBinaryString(b));
Integer c = ' ';
System.out.println(Integer.toBinaryString(c));

出力結果:
100111000101101
101011011111101
3.2コード化

String d = " " ;
byte [] dArray = d.getBytes("UTF-8");
for(Integer index = 0 ; index < dArray.length; index ++){
System.out.println(Integer.toBinaryString(dArray[index] & 0xff));
}
System.out.println();
		
String e = " " ;
byte [] eArray = e.getBytes("UTF-8");
for(Integer index = 0 ; index < eArray.length; index ++){
System.out.println(Integer.toBinaryString(eArray[index] & 0xff));
}

出力結果:
11100100
10111000
10101101
11100101
10011011
10111101
3.比較分析結果
1110_ _ _ _   10_ _ _ _ _ _   10_ _ _ _ _ _
中:100111000101101
(1110)0100   (10)111000      (10)101101
国:101011011111101
(1110)0101   (10)011011      (10)111101
すなわち
3バイトで表すと、
2~4*2~6*2~6=2~16
だから漢字のUnicodeのバイナリは16位です
101011011111101(長さ16)
4.コード化

//  : 
String h = new String(dArray,"UTF-8");
System.out.println(h);
//  : 
String g = " " ;
byte [] gArray = g.getBytes("GBK");
for(Integer index = 0 ; index < gArray.length; index ++){
System.out.println(Integer.toBinaryString(gArray[index] & 0xff));
}
String i = new String(gArray,"UTF-8");
System.out.println(i);


結論:
どんなフォーマットで復号してどんなフォーマットで符号化します
5.java web文字化けし
tomcatの付属コードはISO-8859-1のフォーマットです

String j = new String(str.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(j);


二、コード特徴
1.
長くなる符号化方式.
1~6バイトで1つのシンボルを表し、異なるシンボルによってバイト長が変化する.
Unicode符号化長は、数字、英語、火星文にかかわらず固定されている.だからUnicode符号化は少しスペースがもったいない.UTF 8はunicodeに対する空間浪費現象であり,文字の長さに対して動的である.
2.
UTF-8の符号化規則は簡単で、2つしかありません.
1)バイトのシンボルについては,バイトの第1ビットを0とし,後7ビットをこのシンボルのunicodeコードとする.したがって、UTF-8符号化は、英字ではASCII符号と同じである.
2)nバイトの符号(n>1)については,1バイト目の前nビットがいずれも1,n+1ビット目が0,後バイトの前2ビットが一律に10とする.残りの言及されていないバイナリビットは、すべてこの記号のunicodeコードです.
例:上記のように
ブログの参考:
Javaにおける文字符号化問題と中国語が数バイトを占める問題(ASCII Unicode UTF-8)