Home > Backend Development > PHP Tutorial > How to Convert a String to a Byte Array in PHP?

How to Convert a String to a Byte Array in PHP?

Susan Sarandon
Release: 2024-11-28 02:24:14
Original
819 people have browsed it

How to Convert a String to a Byte Array in PHP?

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);
Copy after login

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) ... }
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template