Home >Backend Development >PHP Problem >How to convert string to byte array in php
In PHP, you can use the pack() function to convert a string into a binary byte stream in a specified format. When you need to convert a string into binary data, you need to pass the string to the pack() function and specify the format. The final return is a byte array.
The following is a sample program that can convert a string into a byte array:
<?php $string = "Hello World"; // 要转换的字符串 $byteArray = unpack('C*', $string); // 将字符串转换成byte数组 print_r($byteArray); // 打印byte数组 ?>
In the above example, the unpack() function is used to convert a string into a byte array, where The first parameter is the format to be specified. C means to parse the data in unsigned characters. The second parameter is the string to be converted, using * means that strings of any length can be processed.
In addition, the byte array can be converted into a string using the pack() function, as shown below:
<?php $byteArray = array(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100); // byte数组 $string = call_user_func_array('pack', array_merge(array('C*'), $byteArray)); // 将byte数组转换成字符串 echo $string; // 打印字符串 ?>
In the above example, a byte array is first defined, and then call_user_func_array( ) function converts a byte array into a string. The first parameter is the format to be specified. C means to parse the data in the form of unsigned characters. The second parameter is the byte array to be converted.
Finally, you can use the echo statement to output the converted string.
In short, in PHP, you can convert strings into byte arrays through the pack() function, and convert byte arrays into strings through the unpack() function to facilitate processing of binary data.
The above is the detailed content of How to convert string to byte array in php. For more information, please follow other related articles on the PHP Chinese website!