Home >Backend Development >PHP Tutorial >How to Get a Hexadecimal Dump of a String in PHP?
Getting a Hexadecimal Dump of Strings in PHP
In PHP, strings represent sequences of characters. However, when dealing with encodings, it may be necessary to inspect the raw bytes that comprise a string. This article explores two methods for obtaining a hexadecimal dump of a string, providing a low-level representation of its binary content.
Method 1: Using bin2hex()
The bin2hex() function converts binary data (bytes) into its hexadecimal representation. To get a hex dump of a string, simply pass it as an argument to bin2hex(). For example:
$string = "Hello World"; $hexDump = bin2hex($string); echo $hexDump;
This will output the following hexadecimal representation:
48656c6c6f20576f726c64
Method 2: Iterating over Characters
For greater control over the formatting, you can iterate over each character in the string and convert its ASCII value to hexadecimal. This can be done using the following code:
$string = "Hello World"; $hexDump = ""; for ($i = 0; $i < strlen($string); $i++) { $hexDump .= str_pad(dechex(ord($string[$i])), 2, '0', STR_PAD_LEFT); } echo $hexDump;
The output will be the same as in Method 1:
48656c6c6f20576f726c64
Both methods provide a hexadecimal representation of the bytes that comprise the string, which can be useful for debugging encoding issues or performing low-level string manipulation.
The above is the detailed content of How to Get a Hexadecimal Dump of a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!