PHP中的字元與位元組的區別及字串與位元組轉換圖文詳解

來源:互聯網
上載者:User
在php中字元是可使用多種不同字元方案或字碼頁來表示的抽象實體。位元組是通過網路傳輸資訊(或在硬碟或記憶體中儲存資訊)的單位。本文還通過執行個體給大家介紹了php中字串與位元組轉換樣本,感興趣的朋友一起看看吧

字元:

字元是可使用多種不同字元方案或字碼頁來表示的抽象實體。例如,Unicode UTF-16 編碼將字元表示為 16 位整數序列,而 Unicode UTF-8 編碼則將相同的字元表示為 8 位位元組序列。公用語言運行庫使用 Unicode UTF-16(Unicode 轉換格式,16 位編碼形式)表示字元。

php在UTF-8編碼下,一個漢字佔3個字元,gbk編碼下只佔2個字元。

位元組(Byte):

位元組是通過網路傳輸資訊(或在硬碟或記憶體中儲存資訊)的單位。

應用:

如果資料庫中表為UTF8編碼,則其中欄位設定為最長10位字元,則最多存入長度為 eg: '我是中1'

下面看下PHP字串與位元組轉換樣本

<?php /** * byte數組與字串轉化類 */class Bytes { /** * 轉換一個String字串為byte數組 * @param $str 需要轉換的字串 * @param $bytes 目標byte數組 * @author Zikie */public static function getBytes($string) { $bytes = array(); for($i = 0; $i < strlen($string); $i++){ $bytes[] = ord($string[$i]); } return $bytes; } /** * 將位元組數組轉化為String類型的資料 * @param $bytes 位元組數組 * @param $str 目標字串 * @return 一個String類型的資料 */public static function toStr($bytes) { $str = ''; foreach($bytes as $ch) { $str .= chr($ch); } return $str; } /** * 轉換一個int為byte數組 * @param $byt 目標byte數組 * @param $val 需要轉換的字串 * */public static function integerToBytes($val) { $byt = array(); $byt[0] = ($val & 0xff); $byt[1] = ($val >> 8 & 0xff); $byt[2] = ($val >> 16 & 0xff); $byt[3] = ($val >> 24 & 0xff); return $byt; } /** * 從位元組數組中指定的位置讀取一個Integer類型的資料 * @param $bytes 位元組數組 * @param $position 指定的開始位置 * @return 一個Integer類型的資料 */public static function bytesToInteger($bytes, $position) { $val = 0; $val = $bytes[$position + 3] & 0xff; $val <<= 8; $val |= $bytes[$position + 2] & 0xff; $val <<= 8; $val |= $bytes[$position + 1] & 0xff; $val <<= 8; $val |= $bytes[$position] & 0xff; return $val; } /** * 轉換一個shor字串為byte數組 * @param $byt 目標byte數組 * @param $val 需要轉換的字串 * */public static function shortToBytes($val) { $byt = array(); $byt[0] = ($val & 0xff); $byt[1] = ($val >> 8 & 0xff); return $byt; } /** * 從位元組數組中指定的位置讀取一個Short類型的資料。 * @param $bytes 位元組數組 * @param $position 指定的開始位置 * @return 一個Short類型的資料 */public static function bytesToShort($bytes, $position) { $val = 0; $val = $bytes[$position + 1] & 0xFF; $val = $val << 8; $val |= $bytes[$position] & 0xFF; return $val; } } ?>

總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.