A Bash Script to Convert brainfuck Code Into C
Brainfuck is a minimalist Turing Complete language. You can read about it here.
The following bash script takes a file with brainfuck code (legal characters are ><,.+-[] any other characters are ignored), and generates its C equivalent code, which can then be compiled with a C compiler and executed.
The output of this script lacks indentation. If you insist on having the C code indented you can achieve this by passing the output through a pipe to “indent”, “astyle” or similar programs.
The script should be called in the following way:
./bf.sh code.bf > code.c
Where code.bf is the file containing the brainfuck code.
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #!/bin/bash echo "int main()" echo "{" echo "char pa[30000] = {0};" echo "char *p = pa;" #following this conversion table: # bf cmd | c equivalent # ----------------------------------- # > | ++p; # < | --p; # + | ++*p; # - | --*p; # . | putchar(*p); # , | *p = getchar(); # [ | while (*p) { # [ | } #----------------------------------- sed -e 's/[^]^[^><,.+-]//g' -e 's/[^(><\+\-\.\,\[\])]//g' \ -e 's/>/\P\Pp;\n/g' -e 's/</MMp;\n/g' -e 's/\+/\+\+\*p;\n/g' \ -e 's/-/--\*p;\n/g' -e 's/\./putchar\(\*p\);\n/g' \ -e 's/,/\*p = getchar\(\);\n/g' -e 's/\[/while \(\*p\) {\n/g' \ -e 's/]/}\n/g' -e 's/P/\+/g' -e 's/M/-/g' "$1" echo "return 0;" echo "}" echo ""; |
You can also download it here: 
Make it executable (chmod +x bf.sh) and you’re ready to go.
For examples of brainfuck programs see the article at Wikipedia.
Enjoy
No related posts.
1 Comment to A Bash Script to Convert brainfuck Code Into C
Leave a Reply
About Me
Tags
Categories
- Algorithms
- Bash
- BlackBerry
- Collaboration
- Command Line
- Cool Tricks
- Easter Eggs
- Ebooks
- Firefox
- Hardware
- Humor
- iPhone
- Linux
- Linux Development
- Linux Kernel
- Networks
- Open Knowledge
- Other
- Productivity
- Programming
- Regular Expressions
- Science
- Security
- Shell Scripts
- Short Posts
- Social Networks
- Thoughts
- Tools
- Vim
- Web Development
- Websites
Popular Posts
Calendar
Archives
- September 2010 (2)
- August 2010 (2)
- July 2010 (5)
- June 2010 (1)
- May 2010 (1)
- April 2010 (3)
- March 2010 (1)
- January 2010 (1)
- December 2009 (2)
- September 2009 (13)
- July 2009 (1)
- June 2009 (6)
- May 2009 (4)
- March 2009 (18)
- February 2009 (10)
- January 2009 (10)
- December 2008 (7)
- November 2008 (8)
- October 2008 (1)
- August 2008 (1)
- July 2008 (1)
- June 2008 (1)

Crazyyyyy !!!!