12

I'm familiar with php's function bin2hex() for converting binary data to its hexadecimal representation.

However, what is the complement function to convert the hexadecimal representation of the data back to binary data?

For example:

$foo = "hello";
$foo = bin2hex($foo);
echo $foo; // Displays 68656c6c6f

How do I turn it back to "hello"?

$foo = "68656c6c6f";
// Now what?

There is no hex2bin() function.

3 Answers 3

17

If you look at PHP's bin2hex page, there's suggested solutions including this one:

$foo = pack("H*" , $foo);
echo $foo;

There's also various implementations of hex2bin that you can choose from.

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

2 Comments

@Tony, did you pick one of the suggested solutions at random, or is this the standard one to use?
This solution seemed short, elegant, and applicable to most all versions of PHP. I can't say if it's the canonical standard one to use, as opposed to some of the other functions provided by submitters to the PHP documentation.
5

Try pack("H*",$foo).

https://www.php.net/manual/en/function.pack.php

Comments

4

For those who have PHP 5.4 and above, there's a standard way of doing this:

<?php $bin = hex2bin("6578616d706c65206865782064617461"); var_dump($bin); ?>

The output of the code above should be similar to:

string(16) "example hex data"

Gotten off of the PHP hex2bin page.

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.