a weblog about programming, hacking, linux, and other randomness

My Photo
I'm a Programmer, Hobby Hacker, and Linux Freak.

Wednesday, April 22, 2009

Brainfuck Code Generation Using PHP

"The Brainfuck language is a programming language noted for its extreme minimalism. Designed to challenge and amuse programmers, it is not suitable for practical use."... But it sure is fun!

After reading the article How to Shoot Yourself in the Foot in Any Programming Language, I was challenged to learn this language due to it's confusing syntax. Turns out, it's pretty simple. If you understand arrays and pointers then you've got it. I can definitely see how it can be a pain to use though. One misplaced ">" and you're left searching through a maze of pointers.

I created this script using PHP to convert plain text into BF code. Use it to pass messages to your friends...well nerdy friends.
if(!$text = @$argv[1]) die('Usage: '.$argv[0].' text');

$string = '++++++++++[';

for($i = 0; $i < strlen($text); $i++) {
$value = ord($text[$i]);
$remainder = $value % 10;
$value -= $remainder;

if($value > 10) {
$string .= '>';
for($x = 0; $x < $value / 10; $x++)
$string .= '+';
}
}

for($i = 0; $i < strlen($text); $i++) {
$value = ord($text[$i]);
$remainder = $value % 10;
$value -= $remainder;

if($value > 10)
$string .= '<';
}

$string .= '-]';

for($i = 0; $i < strlen($text); $i++) {
$value = ord($text[$i]);
$remainder = $value % 10;
$value -= $remainder;

$string .= '>';
for($x = 0; $x < $remainder; $x++)
$string .= '+';
$string .= '.';
}

echo $string;
Example output of php script.php "http://ryonsherman.blogspot.com":
++++++++++[>++++++++++>+++++++++++>+++++++++++>+++++++++++>+++++>++++>++++>+++
++++++++>++++++++++++>+++++++++++>+++++++++++>+++++++++++>++++++++++>++++++++++>++++
+++++++>++++++++++>+++++++++>+++++++++++>++++>+++++++++>++++++++++>+++++++++++>+++++
+++++>+++++++++++>+++++++++++>+++++++++++>+++++++++++>++++>+++++++++>+++++++++++>+++
+++++++<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]>++++.>++++++.>++++++.>++.>++++++++.>+++++++
.>+++++++.>++++.>+.>+.>.>+++++.>++++.>+.>++++.>+++++++++.>+++++++.>.>++++++.>+++++++
+.>++++++++.>+.>+++.>+++++.>++.>+.>++++++.>++++++.>+++++++++.>+.>+++++++++.

0 comments:

Post a Comment