php method to convert into byte array: 1. Create a PHP sample file; 2. Convert a string string into a byte array through "public static function getbytes($str) {...}" Can.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
How to convert php into a byte array?
php converts byte[] data type
The code is as follows:
= 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; } }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert php into byte array. For more information, please follow other related articles on the PHP Chinese website!