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: Brainfuck to C converter 672 bytes

Make it executable (chmod +x bf.sh) and you’re ready to go.

For examples of brainfuck programs see the article at Wikipedia.

Enjoy ;)

If you enjoyed this post, make sure you subscribe to my RSS feed!

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

No related posts.

Tags: , , ,

Sunday, June 14th, 2009 Programming

1 Comment to A Bash Script to Convert brainfuck Code Into C

  • Mayank says:

    Crazyyyyy !!!! :D

  • Leave a Reply

    my email
    my photo
    Hi,
    My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and a BSc. in electrical engineering from The Electrical Engineering school , Technion , Israel.
    I'm a Verification Engineer in Mellanox Technologies Ltd.
    I love Linux, the Command Line and the OpenSource Community.
    I used to write Poems (Arabic) when I was able to find time for this.
    June 2009
    S M T W T F S
    « May   Jul »
     123456
    78910111213
    14151617181920
    21222324252627
    282930  
    SEO Powered by Platinum SEO from Techblissonline

    Twitter links powered by Tweet This v1.7.4, a WordPress plugin for Twitter.