Fun

A text-to-Brainfuck/RNA converter in ANSI C99

Brainfuck encoder

The following small ANSI C99 program reads a String from stdin and prints out a Brainfuck program that prints the same String on stdout.

Compile using gcc -o bf bf.c

Use it like this:

cat my.txt | ./bf > my.bf

Source code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    unsigned char c;
    unsigned char curval = 0;
    //Initialize reg+1 with 8
    while(1) {
        c = getchar();
        if(feof(stdin)) {break;}
        while(curval != c) {
            if(curval < c) {
                putchar('+');
                curval++;
            } else if(curval > c) {
                putchar('-');
                curval--;
            }
        }
        putchar('.');
    }
}

How does it work?

Basically it uses just one of the registers of the Brainfuck Turing machine and incremets or decrements the register to be able to print out the next byte. It doesn’t use any of the more ‘advanced’ features in Brainfuck like loops.

Continue reading →

Posted by Uli Köhler in C/C++, Fun