In PHP programming, sometimes we need to convert a string into a byte array for use during network transmission or data processing. This article explains how to convert a string to a byte array using PHP.
In PHP, strings can be defined using single quotes or double quotes. For example:
$str1 = 'hello world'; $str2 = "hello world";
Each character in the string has a corresponding ASCII code value, which can be obtained using theord()
function. For example:
$ascii = ord('A'); echo $ascii; // 输出 65
In order to convert a string into a byte array, we need to first convert the ASCII code value of each character into a binary representation, and then concatenate each binary character into a byte. The following is the implementation code:
/** * 将字符串转换为 byte 数组 * * @param string $str * @return array */ function strToByteArray(string $str): array { $len = strlen($str); $byteArray = array(); for ($i = 0; $i < $len; $i++) { $byteArray[] = ord($str[$i]); } return $byteArray; } $str = "hello"; $byteArray = strToByteArray($str); print_r($byteArray); // 输出 [104, 101, 108, 108, 111]
In the above code, we use thestrlen()
function to get the string length, and then use theord()
function to convert each The character's ASCII code value is written into an array. The final returned array is a byte array.
The above code simply converts a string into a byte array. If network transmission or data processing is involved, the byte order issue also needs to be considered. The byte order in PHP is consistent with the host byte order, so no byte order conversion is required.
However, if you need to interact with other languages (such as Java, C#, etc.), you need to consider the issue of byte order. At this time, you can use thepack()
andunpack()
functions to handle byte order. For specific usage methods, please refer to the PHP official documentation.
To summarize, converting a string to a byte array in PHP can be achieved by converting the ASCII code value of each character into a binary representation, and then concatenating each binary character into a byte. If there are endianness issues involved, you can use thepack()
andunpack()
functions to deal with them.
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!