Home > Backend Development > PHP Tutorial > How to Get a Hexadecimal Dump of a String in PHP?

How to Get a Hexadecimal Dump of a String in PHP?

Mary-Kate Olsen
Release: 2024-12-18 09:53:11
Original
244 people have browsed it

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

This will output the following hexadecimal representation:

48656c6c6f20576f726c64
Copy after login
Copy after login

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

The output will be the same as in Method 1:

48656c6c6f20576f726c64
Copy after login
Copy after login

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!

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