The article provides you with an example of conversion between PHP string and byte array. I hope the article will be helpful to all students.
The code is as follows | Copy code |
/** * Byte array and string conversion class */ class Bytes { /** * Convert a String to a byte array * @param $str The string to be converted * @param $bytes target byte array * @author Zikie */ Public static function getBytes($string) { $bytes = array(); for($i = 0; $i < strlen($string); $i++){ $bytes[] = ord($string[$i]); } return $bytes; } /** * Convert byte array to String type data * @param $bytes byte array * @param $str target string * @return a String type data */ Public static function toStr($bytes) { $str = ''; foreach($bytes as $ch) { $str .= chr($ch); } return $str; } /** * Convert an int to a byte array * @param $byt target byte array * @param $val The string to be converted * */ 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; } /** * Read an Integer type data from the specified position in the byte array * @param $bytes byte array * @param $position specified starting position * @return an Integer type data */ 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; } /** * Convert a short string to a byte array * @param $byt target byte array * @param $val The string to be converted * */ Public static function shortToBytes($val) { $byt = array(); $byt[0] = ($val & 0xff); $byt[1] = ($val >> 8 & 0xff); return $byt; } /** * Read a Short type data from the specified position in the byte array. * @param $bytes byte array * @param $position specified starting position * @return a Short type data */ Public static function bytesToShort($bytes, $position) { $val = 0; $val = $bytes[$position + 1] & 0xFF; $val = $val << 8; $val |= $bytes[$position] & 0xFF; return $val; } } ?> |