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

How to convert string to byte array in php

PHPz
PHPzOriginal
2023-04-20 13:53:461034browse

In PHP, we can use several methods to convert a string to a byte array. In this article, we will focus on the two most common methods.

Method 1: Use str_split function

str_split(string$string, int$split_length = 1): Split the string into substrings, put them in an array, and return the array. The length of each string will be the length specified by the split_length parameter. If split_length is not specified, it defaults to 1.

The following is a sample code to convert a string to a byte array:

$str = "Hello World!";
$bytes = str_split($str);

foreach($bytes as $byte) {
    echo ord($byte) . " ";
}

In this sample code, we have used the ord function to convert each character to ASCII code, and used foreach Loop prints a byte array to the console. The output will be:

72 101 108 108 111 32 87 111 114 108 100 33

Method Two: Using the unpack function

This method requires using the pack function to pack the string into binary data. In addition, when using the unpack function, you need to specify the packed data type and convert the return value to a byte array.

The following is the sample code:

$str = "Hello World!";
$bytes = unpack('C*', pack('H*', bin2hex($str)));

foreach($bytes as $byte) {
    echo $byte . " ";
}

In this sample code, we have used bin2hex to convert the string into a hexadecimal string, and then used pack to pack it into binary data. When using unpack, we unpack the data using C type shared symbols and print the byte array using a foreach loop.

The output will be:

72 101 108 108 111 32 87 111 114 108 100 33

To summarize, these are two ways to convert a string to a byte array in PHP. Understanding how these methods work is critical for developers who need to perform various encryption/decryption operations.

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