- <?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;
- }
- }
- ?>
新聞熱點
疑難解答