Thursday, May 6, 2010

Translating brainfuck code to ANSI-C code with BrainfuckToC

This is my latest project. An application that translates brainfuck code to ANSI-C code.

To download the sources, visit the Google Code brainfucktoc page.

I would also like to thank Reuben Sammut who is a contributer to the project.

Usage

bftoc <source file>

Example:

bftoc bfcode.b

This will take a brainfuck source file and output its equivalent C code.

If you want to redirect the output to a text file, run bftoc as follows:

bftoc bfcode.b > bfcode.c

Examples

Hello World
Input:
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
Output:
#include <stdio.h>
#include <stdlib.h>

int main () {
    char *ptr = calloc(10000, sizeof *ptr), *start = ptr;
    int i = 0;

    *ptr += 10;
    while (*ptr) {
        ++ptr;
        *ptr += 7;
        ++ptr;
        *ptr += 10;
        ++ptr;
        *ptr += 3;
        ++ptr;
        ++*ptr;
        ptr -= 4;
        --*ptr;
    }

    ++ptr;
    *ptr += 2;
    putchar(*ptr);
    ++ptr;
    ++*ptr;
    putchar(*ptr);
    *ptr += 7;
    putchar(*ptr);
    putchar(*ptr);
    *ptr += 3;
    putchar(*ptr);
    ++ptr;
    *ptr += 2;
    putchar(*ptr);
    ptr -= 2;
    *ptr += 15;
    putchar(*ptr);
    ++ptr;
    putchar(*ptr);
    *ptr += 3;
    putchar(*ptr);
    *ptr -= 6;
    putchar(*ptr);
    *ptr -= 8;
    putchar(*ptr);
    ++ptr;
    ++*ptr;
    putchar(*ptr);
    ++ptr;
    putchar(*ptr);

    free(start);
    return 0;
}