<?php /** * byte數組與字符串轉化類 * @author ZT */ class Bytes { /** * 轉換一個string字符串為byte數組 * @param $str 需要轉換的字符串 * @param $bytes 目標byte數組 */ public static function getbytes($str) { $len = strlen($str); $bytes = array(); for($i=0;$i<$len;$i++) { if(ord($str[$i]) >= 128){ $byte = ord($str[$i]) - 256; }else{ $byte = ord($str[$i]); } $bytes[] = $byte ; } 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; } }