6

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?

1
  • 2
    You should choose an accepted answer. The poster gets reputation credit for it. Commented Jan 19, 2015 at 14:14

2 Answers 2

18

Use pack() and unpack():

function hex2str($hex) {
  return pack('H*', $hex);
}

function str2hex($str) {
  $unpacked = unpack('H*', $str);
  return array_shift($unpacked);
}

$txt = 'This is test';
$hex = str2hex($txt);
$str = hex2str($hex);

echo "{$txt} => {$hex} => {$str}\n";

would produce

This is test => 546869732069732074657374 => This is test

Sign up to request clarification or add additional context in comments.

3 Comments

This is awesome, why unpack() works, while dechex() not? and furthermore, unpack is not just for binary strings?
This will trigger a notice: PHP Notice: Only variables should be passed by reference
Ah, it was about directly passing result of unpack() to array_shift(). Fixed, thanks.
1

Use a function like this:

<?php
function bin2hex($str) {
    $hex = "";
    $i = 0;
    do {
        $hex .= dechex(ord($str{$i}));
        $i++;
    } while ($i < strlen($str));
    return $hex;
}

// Look what happens when ord($str{$i}) is 0...15
// you get a single digit hexadecimal value 0...F

// bin2hex($str) could return something like 4a3,
// decimals(74, 3), whatever the binary value is of those.

function hex2bin($str) {
    $bin = "";
    $i = 0;
    do {
        $bin .= chr(hexdec($str{$i}.$str{($i + 1)}));
        $i += 2;
    } while ($i < strlen($str));
    return $bin;
}

// hex2bin("4a3") just broke. Now what?

// Using sprintf() to get it right.
function bin2hex($str) {
    $hex = "";
    $i = 0;
    do {
        $hex .= sprintf("%02x", ord($str{$i}));
        $i++;
    } while ($i < strlen($str));
    return $hex;
}

// now using whatever the binary value of decimals(74, 3)
// and this bin2hex() you get a hexadecimal value you can
// then run the hex2bin function on. 4a03 instead of 4a3.
?>

Source: http://php.net/manual/en/function.bin2hex.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.