Home >Backend Development >PHP Problem >How to convert string to byte array in php

How to convert string to byte array in php

PHPz
PHPzOriginal
2023-04-20 15:07:21958browse

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(&#39;C*&#39;, $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(&#39;pack&#39;, array_merge(array(&#39;C*&#39;), $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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn