Steve Jenson's blog

BF to C in awk

BF to C in awk

I wrote a Brainfuck to C translator in awk. It only takes a few minutes and I noticed that no awk version of this existed.

I haven't run it through it's paces (I just wrote a few small brainfuck programs to test it out) so if you find a bug, please let me know.
    #!/sw/bin/awk -f                                                                                                                                                                           
    # a brainfuck to C translator.                                                                                                                                                             
    # Needs a recent version of gawk, if on OS X,                                                                                                                                              
    # try using Fink's version.                                                                                                                                                                
    # steve jenson                                                                                                                                                                             
    BEGIN {
    print "#include <stdio.h>\n";
    print "int main() {";
    print "  int c = 0;";
    print "  static int b[30000];\n";
    #Note: the order in which these are                                                                                                                                                      
    #substituted is very important.                                                                                                                                                          
    gsub(/\]/, "  }\n");
    gsub(/\[/, "  while(b[c] != 0) {\n");
    gsub(/\+/, "  ++b[c];\n");
    gsub(/\-/, "  --b[c];\n");
    gsub(/>/, "  ++c;\n");
    gsub(/</, "  --c;\n");
    gsub(/\./, "  putchar(b[c]);\n");
    gsub(/\,/, "  b[c] = getchar();\n");
    print $0
    END {
    print "\n  return 0;";
    print "}";
update: You can blame this on Evan Martin, his recent post wherein half the universe decided to weigh in about PHP had a mention of mod_bf. Am I easily distracted or what?

update: Last update, I swear. Darius said that I don't need to initialize b if I declare it static. Also, I realized that my previous version wouldn't understand if you had multiple operators on the same line since it was matching records and not fields. This version works on all of the programs I tried in the Brainfuck archive (as long as you strip comments).

# — 03 December, 2004