數據庫字段定義 VARCHAR(10) 指字符數,UTF-8下最多存3-4個漢字。
class Bytes {
// 字符串轉字節數組
public static function getBytes($string) {
$bytes = array();
for ($i = 0; $i < strlen($string); $i++) {
$bytes[] = ord($string[$i]);
}
return $bytes;
}
// 字節數組轉字符串
public static function toStr($bytes) {
$str = '';
foreach ($bytes as $ch) {
$str .= chr($ch);
}
return $str;
}
// 整數轉4字節數組(大端序)
public static function integerToBytes($val) {
return array(
($val >> 24) & 0xff,
($val >> 16) & 0xff,
($val >> 8) & 0xff,
$val & 0xff
);
}
// 字節數組讀取整數
public static function bytesToInteger($bytes, $position) {
$val = 0;
$val = ($bytes[$position] << 24) |
($bytes[$position+1] << 16) |
($bytes[$position+2] << 8) |
($bytes[$position+3] & 0xff);
return $val;
}
// 同理提供 shortToBytes / bytesToShort
}
網絡協議封裝、二進制文件解析、加密算法實現等需字節級操作的場景。