Binary to Text and the other way around

nike_guy_man's picture

They have: 840 posts

Joined: Sep 2000

Hello
I was wondering how you could convert binary code to text or text to binary.
I have no clue how I'd do this, and I'd like to know.
Thanks

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

If you mean from character to ASCII (A=65, etc.), then try these:
chr(), ord()

nike_guy_man's picture

They have: 840 posts

Joined: Sep 2000

Thats not what I want...
I have a string of 0s and 1s... how do I turn them into ASCII text?

Suzanne's picture

She has: 5,507 posts

Joined: Feb 2000

http://phpbuilder.com/columns/florian19991014.php3 this might be a starting place?

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

I just wrote this up real quick...

script:

<?php
error_reporting
(0);


echo \
"<html>\n\";
echo \"<body>\n\";
echo \"<pre>\n\";

$ascii = \"my string\";

echo \"<font size=\\"
+1\\">\";
echo \"<b>String to Binary</b>\";
echo \"</font>\n\";
echo \"\n\";

echo \"ascii string:\n
$ascii\n\";
echo \"\n\";

$binary = NULL;

for (
$i=0, $letter=$ascii[$i]; $i<strlen($ascii); $letter=$ascii[++$i]) {
    printf(\"%s %3d %08d\n\",
$letter, ord($letter), decbin(ord($letter)));
   
$binary .= sprintf(\"%08d\", decbin(ord($letter)));
}

echo \"\n\";
echo \"binary string:\n\";
echo \"
$binary\n\";
echo \"\n\";
echo \"\n\";


echo \"<font size=\\"
+1\\">\";
echo \"<b>Binary to String</b>\";
echo \"</font>\n\";
echo \"\n\";

$string = NULL;

for (
$i=0, $letter=substr($binary, $i, 8); ($i+8)<=strlen($binary); $i+=8, $letter=substr($binary, $i, 8)) {
    printf(\"%08d %3d %s\n\",
$letter, bindec($letter), chr(bindec($letter)));
   
$string .= sprintf(\"%s\", chr(bindec($letter)));
}

echo \"\n\";
echo \"ascii string:\n\";
echo \"
$string\n\";
echo \"\n\";

echo \"\n\";
echo \"</pre>\n\";
echo \"</body>\n\";
echo \"</html>\n\";
?>

output:
String to Binary

ascii string:
my string

m 109 01101101
y 121 01111001
   32 00100000
s 115 01110011
t 116 01110100
r 114 01110010
i 105 01101001
n 110 01101110
g 103 01100111

binary string:
011011010111100100100000011100110111010001110010011010010110111001100111


Binary to String

01101101 109 m
01111001 121 y
00100000  32 
01110011 115 s
01110100 116 t
01110010 114 r
01101001 105 i
01101110 110 n
01100111 103 g

ascii string:
my string
'Does that do what you want?

Mark Hensler
If there is no answer on Google, then there is no question.

Suzanne's picture

She has: 5,507 posts

Joined: Feb 2000

wow. that's alarmingly cool. I can't think of a reason to use it, but I'm no programmer (clearly). Wow.

nike_guy_man's picture

They have: 840 posts

Joined: Sep 2000

Thanks it seems to work fine.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.