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 Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

Related posts:

  1. Brainfuck String Generator Generator
  2. Tiny Bash Functions to Convert Between Numeric Representations
  3. Make Shell Scripts Executable By Default
  4. Strip the File Name Suffix off a Bash Variable
  5. Convert camelCase to Underscores Using sed

Tags: , , ,

Sunday, June 14th, 2009 Programming

Leave a Reply

my email
Already a member?
Login
Login using Facebook:
Last visitors
my photo
Hi,
My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and am currently studying for a BSc. in electrical engineering at The Electrical Engineering school , Technion , Israel.
I work at the verification dept. 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  
Firefox Logo Crystal
SEO Powered by Platinum SEO from Techblissonline

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