Converting String to Byte Array in PHP
Converting a string to a byte array in PHP requires translating individual characters into their corresponding byte values. For a functionality similar to Java's getBytes() method, you can employ the following approach:
$byte_array = unpack('C*', $string);
The unpack() function with the 'C' format flag decomposes the string into an array of integer values representing the ASCII codes of each character. These values range from 0 to 255, effectively converting the string into a byte array.
For example, consider the string "The quick fox jumped over the lazy brown dog":
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog'); var_dump($byte_array); // Output: array(44) { ... (hexadecimal values) ... }
The resulting array $byte_array contains the integer values corresponding to each character's ASCII code in hexadecimal format.
It's important to note that var_dump() displays the values in hexadecimal format by default. However, they can be easily converted to their decimal equivalents using the chr() function, if desired.
The above is the detailed content of How to Convert a String to a Byte Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!