Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hexadecimal representation of data to binary data in PHP?

Tags:

string

php

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.

like image 883
Marcus Adams Avatar asked Apr 08 '10 19:04

Marcus Adams


People also ask

How do you convert from hexadecimal to binary?

Hexadecimal to binarySplit the hex number into individual values. Convert each hex value into its decimal equivalent. Next, convert each decimal digit into binary, making sure to write four digits for each value. Combine all four digits to make one binary number.

Why do we convert hexadecimal to binary?

Computers can understand only binary language. So all other number systems given by the user will be stored in binary form in computers. Thus, the conversion of hexadecimal to binary is very important.

What does hex2bin do in PHP?

The hex2bin() function converts a string of hexadecimal values to ASCII characters.


2 Answers

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.

like image 60
Tony Miller Avatar answered Sep 21 '22 06:09

Tony Miller


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

http://us3.php.net/manual/en/function.pack.php

like image 25
Weston C Avatar answered Sep 23 '22 06:09

Weston C