PHP: Convert a string to hex and vice versa

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

Working with different data formats is a common task for developers, and converting between them can be crucial. In this tutorial, we’ll explore how to convert a string to its hexadecimal representation and vice versa in PHP, diving into practical code examples that will enhance your manipulation finesse with strings and hex data.

Understanding Hexadecimal Conversion

Before we jump into code, let’s get a brief understanding of what hexadecimal conversion entails. A hexadecimal (or hex) is a base-16 number system, which is a convenient way to express binary data. Each hex digit represents four binary digits, which means two hex digits can represent one byte of data.

In PHP, we often need to convert strings to hexadecimal to prepare data for transmission or storage, and to convert hex back to strings for readability or processing.

Basic String to Hex

The simplest way to convert a string to hexadecimal is by using PHP’s built-in bin2hex function. This function converts each character of the plain text to its corresponding hex value.

$string = "Hello, World!";
$hex = bin2hex($string);
echo $hex; // Outputs: 48656c6c6f2c20576f726c6421

Basic Hex to String

To convert from hex back to a string, we use the hex2bin function which performs the inverse operation of bin2hex.

$hex = '48656c6c6f2c20576f726c6421';
$string = hex2bin($hex);
echo $string; // Outputs: Hello, World!

Unpacking and Packing Data

Beyond single function calls, PHP offers more control through unpack and pack functions, which can be particularly useful when working with binary data streams.

// Unpack a string into an array of hex values
$unpackedArray = unpack('H*', "Hello, World!");
$hex = array_shift($unpackedArray);
echo $hex; // 48656c6c6f2c20576f726c6421

// Pack an array of hex values back into a string
$packedString = pack('H*', $hex);
echo $packedString; // Hello, World!

Working With Multibyte Strings

In dealing with multibyte character encodings like UTF-8, proper handling is necessary for accurate conversion. The mb_* functions in PHP offer this functionality.

$string = "こんにちは";
$hex = bin2hex($string);
echo $hex; // Outputs: e38193e38293e381abe381a1e381af

Further Manipulating Hex Strings

You can also manually manipulate hexadecimal strings by splitting, joining, or even performing arithmetic operations on them, which becomes extremely powerful when you need to perform low-level data manipulation for things like cryptographic functions.

See also: Turn a PHP string into an array of characters

Advanced Conversion Techniques

For more complex scenarios, such as working with binary files or encrypting data, functions like openssl_encrypt and openssl_decrypt may come into play. Converting strings to hexadecimal can be a part of the process when generating secure hashes or storing binary safe text in databases.

// Example of using hex conversion in cryptographic functions
$string = 'SecureData';
$key = 'secret';
$method = 'AES-256-CBC';
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
$encrypted = openssl_encrypt($string, $method, $key, 0, $iv);
$hex = bin2hex($encrypted);
echo $hex;

$binary_data = hex2bin($hex);
$decrypted = openssl_decrypt($binary_data, $method, $key, 0, $iv);
echo $decrypted; // outputs: SecureData

Best Practices

When working with hexadecimal conversions, always ensure that input data is properly validated and sanitized to prevent security vulnerabilities. Misinterpretation of encoding can lead to data corruption or security issues. Also, keep in mind PHP’s integer limitation when working with large binary values and use strings to avoid overflow.

Conclusion

To wrap up, converting strings to hex and vice versa is a fundamental process in PHP, and it can be approached with built-in functions for simplicity, or with deeper logic for fine-grained control and advanced use cases. Understanding and using these conversions are important skills in a PHP developer’s arsenal for data handling and security. Utilize the provided examples as a starting point, and don’t be afraid to expand upon them as your projects necessitate more complex data manipulation.