1

I came up with the PHP code below which converts a binary string 00000010 to the string "representation" and then later I convert it back to the binary string, however it's not getting back the same original binary string 00000010. The code below works perfectly with 10000010, 11000010... but for some strange reason it does not work with 00000010. Why?

$binary = '00000010';
echo $binary . "\n";

$temp = pack('H*',dechex(bindec($binary)));
echo str_pad(decbin(ord($temp)),8,'0',STR_PAD_LEFT);

OUTPUT:

00000010
00100000

I know some string "representation" of some binary strings are not visible/printable chars, but I dont care printing those chars. I just want to convert it to that string "representation" and back, but it's not working. What I am doing wrong?

EDIT:

After great help of @Rocket Hazmat the code started working for some binaries but not for others. The code below, for example, does not look to work, it outputs 0 instead of 10101010.

$binary = '10101010';
$temp = pack('C',base_convert($binary,2,16));
echo base_convert(ord($temp),16,2);

1 Answer 1

1

Using pack() with h* (or h) is what you want here. You are reading it in as a hex value (after converting from binary), so you want pack to see it as a hex value.

$temp = pack('h', base_convert($binary, 2, 16));

The problem was when you convert it back. ord returns you a base 10 number. I was incorrectly converting it as a hex (base 16) value:

base_convert(ord($temp), 10, 2)

Though, after looking at the code again, I think you don't even need pack() here. You are using ord(), so we can use its opposite, chr():

$temp = chr(base_convert($binary, 2, 10));

chr() wants a (base 10) int though, not a hex value, so let's use that.

What seems to be working is the following:

$temp = chr(base_convert($binary, 2, 10));
echo str_pad(base_convert(ord($temp), 10, 2), 8, '0', STR_PAD_LEFT);
Sign up to request clarification or add additional context in comments.

12 Comments

So how do I create a code that knows when to use H and h? Because you are right, using h* solves the problem to convert 00000010 go and back, but it breaks all the other binary string that I tried with H*! BTW, thanks for pointing about the * :)
@Samul: I see the issue. Instead of h or H, you actually want C. And you can simplify the dechex/bindec/dechex using base_convert. I'll update the answer.
Worked perfectly my friend, you nailed it! Thanks for not only posting the code, your comments were very valuable!
My friend, I tried your most recent code with the string 10101010 and it does not work, it returns 0. Maybe I am doing something wrong?
@Samul I am working on it. I think I see what I did wrong.
|

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.