Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to binary then back again using PHP

Tags:

php

binary

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

like image 704
locoboy Avatar asked Jun 17 '11 07:06

locoboy


2 Answers

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));
like image 145
Francois Deschenes Avatar answered Nov 19 '22 10:11

Francois Deschenes


Yes, sure!

There...

$bin = decbin(ord($char));

... and back again.

$char = chr(bindec($bin));
like image 39
SteeveDroz Avatar answered Nov 19 '22 10:11

SteeveDroz