Re: [問題] 字串經過encode之後的length

作者: cutekid (可愛小孩子)   2018-11-17 15:06:00
$str1 = "中文"; # UTF-8 Encoding
中: 0xE4 0xB8 0xAD (UTF-8 Encoding)
文: 0xE6 0x96 0x87 (UTF-8 Encoding)
encode("UTF-8", $str1)時,$str1 被當作 Latin-1 在看(因為這時 UTF-8 flag = off)
所以就變成 "\x{e4}\x{b8}\x{ad}\x{e6}\x{96}\x{87}" 共 6 個 Latin-1 字元轉 UTF-8
總共 12 個 Bytes: 0xC3 0xA4 0xC2 0xB8 0xC2 0xAD 0xC3 0xA6 0xC2 0x96 0xC2 0x87
結論:
1. 純英文的時候,Latin-1 和 UTF-8 編碼相同(都佔 1 個 Byte),所以 Byte 數不會變
2. 有中文的時候,一個字佔 3 個 Bytes(UTF-8),被當作 Latin-1 看就變成 3 個字元
Latin-1 大於 0x7F 的字元,轉成 UTF-8 佔 2 個 Bytes
所以就可以解釋: 為什麼 length of encode("UTF-8", "ABC呢") = 9 (3 + 3 x 2)
※ 引述《kipi91718 (Renewal Process)》之銘言:
: 各位大大好,初次在本版發文,請多指教。
: 在perldoc上面有敘述到:
: When you run $octets = encode("utf8", $string) , then $octets might not be
: equal to $string. Though both contain the same data, the UTF8 flag for
: $octets is always off. When you encode anything, the UTF8 flag on the result
: is always off, even when it contains a completely valid utf8 string.
: https://perldoc.perl.org/Encode.html
: 我測試了以下三個狀況,在perl 5.26.1的環境下確認原始字串都是utf-8,
: 但在encode之後用length去檢測發現結果不太能完全理解。
: 1. $str1 = "中文";
: length( $str1 ); #答案為6,因為UTF8 flag off,這是在算byte數,中文佔3 Bytes
:
: Encode::_utf8_on( $str1 );
: length( $str1 ); #答案為2,因為UTF8 flag on,這是在算中文字數量
:
: Encode::_utf8_off( $str1 );
: length( $str1 ); #答案為為6,一樣是UTF8 flag off的狀況,為byte數
:
: $str1_e = encode("UTF-8", str1);
: length($str1_e); #答案為12,不知道是在計算什麼的數量才會得到12
:
: 2. $str2 = "English";
: length( $str2 ); #因為英文本來就只佔了1 Byte,所以答案為7
:
: Encode::_utf8_on( $str2 );
: length( $str2 ); #算字數一樣答案為7
:
: Encode::_utf8_off( $str2 );
: length( $str2 ); #7 Bytes
:
: $str2_e = encode("UTF-8", str2);
: length( $str2); #沒改變,一樣是7,是什麼原因呢?
: 3. $str3 = "ABC呢";
: length( $str3 ); #英文 1*3 = 3 Bytes + 中文 3*1 = 3 Bytes 答案為6 Bytes
:
: Encode::_utf8_on( $str3 );
: length( $str3 ); #共3英文字+1中文字 = 4個字
:
: Encode::_utf8_off( $str3 );
: length( $str3 ); #6,因為6 Bytes
:
: $str3_e = encode("UTF-8", str3);
: length( $str3_e); #答案為9,所以看起來中文在這情況下的結果是每字+6?
:
: 經過以上實測,比較有疑問的是encode到底做了什麼? 以至於讓length去偵測時,中文
: 會回傳6呢?
: 又問得更根本,在encode回來之後$octets送進length時,
: 究竟是被當作什麼型態在處理呢?
: 請版上專業的大大解惑,我可以200P作為微薄的謝禮,謝謝!
作者: kipi91718 (正港台灣人)   2018-11-17 21:34:00
感謝 紅包已發

Links booklink

Contact Us: admin [ a t ] ucptt.com