Given a string that may contain any character (including a unicode characters), how can I convert this string into hexadecimal representation, and then reverse and obtain from hexadecimal this string?
Hex encoding is performed by converting the 8 bit data to 2 hex characters. The hex characters are then stored as the two byte string representation of the characters. Often, some kind of separator is used to make the encoded data easier for human reading.
Hexadecimal numerals are widely used by computer system designers and programmers. As each hexadecimal digit represents four binary digits (bits), it allows a more human-friendly representation of binary-coded values.
Hex encoding is a transfer encoding in which each byte is converted to the 2-digit base-16 encoding of that byte (preserving leading zeroes), which is then usually encoded in ASCII. It is inefficient, but it is a simple, commonly-used way to represent binary data in plain text.
Use pack()
and unpack()
:
function hex2str( $hex ) {
return pack('H*', $hex);
}
function str2hex( $str ) {
return array_shift( unpack('H*', $str) );
}
$txt = 'This is test';
$hex = str2hex( $txt );
$str = hex2str( $hex );
echo "{$txt} => {$hex} => {$str}\n";
would produce
This is test => 546869732069732074657374 => This is test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With