Convert string to binary then back again using PHP

locoboy picture locoboy · Jun 17, 2011 · Viewed 150.2k times · Source

Is there a way to convert a string to binary then back again in the standard PHP library?

To clarify what I'm trying to do is store a password on a database. I'm going to convert it first using a hash function then eventually store it as binary.


I've found the best way is to use this function. Seems to hash and output in binary at the same time.

http://php.net/manual/en/function.hash-hmac.php

Answer

Francois Deschenes picture Francois Deschenes · Jun 17, 2011

You want to use pack and base_convert.

// Convert a string into binary
// Should output: 0101001101110100011000010110001101101011
$value = unpack('H*', "Stack");
echo base_convert($value[1], 16, 2);

// Convert binary into a string
// Should output: Stack
echo pack('H*', base_convert('0101001101110100011000010110001101101011', 2, 16));