Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding/decoding string in hexadecimal and back

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?

like image 293
Oto Shavadze Avatar asked Nov 24 '12 13:11

Oto Shavadze


People also ask

How do I encode a hex 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.

What is hexadecimal decoding?

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.

Is hexadecimal a type of encoding?

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.


1 Answers

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

like image 109
Marcin Orlowski Avatar answered Sep 21 '22 07:09

Marcin Orlowski