php字串與byte位元組數組轉化類樣本

來源:互聯網
上載者:User
 代碼如下 複製代碼
<?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.