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

How to convert php string to byte array

藏色散人
藏色散人Original
2021-07-13 10:10:185653browse

How to convert string to byte array in php: First create a PHP sample file; then use the "function strToBytes($string){...}" method to convert string to byte array.

How to convert php string to byte array

The operating environment of this article: Windows7 system, PHP7.1 version, DELL G3 computer

php How to convert a string to a byte array ?

Conversion between strings and byte arrays in PHP

You often see this type in java:

byte[] IV = { 0, 0, 0, 0, 0, 0, 0, 0 }

Unfortunately, PHP, as a weakly typed language, does not have so many types. The following provides examples of mutual conversion of strings and byte arrays in PHP:

/**
 * Byte数组转字符串
 * @param  array $bytes
 * @return string
 */
function bytesToStr($bytes)
{
    $str = '';
    foreach ($bytes as $ch) {
        $str .= chr($ch);
    }
    return $str;
}
/**
 * 字符串转Byte数组
 * @param  string $string
 * @return array
 */
function strToBytes($string)
{
    $bytes = array();
    for ($i = 0; $i < strlen($string); $i++) {
        $bytes[] = ord($string[$i]);
    }
    return $bytes;
}

Recommended learning: " PHP video tutorial

The above is the detailed content of How to convert php string to byte array. 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