Skip to content

Instantly share code, notes, and snippets.

@masnnuller
Created November 22, 2011 03:38
Show Gist options
  • Save masnnuller/1384825 to your computer and use it in GitHub Desktop.
Save masnnuller/1384825 to your computer and use it in GitHub Desktop.
import java.io.*;
public class BrainFuckCompile {
static StringBuffer ostr;
static char[] fileRead(String inputFilePath) throws IOException{
char[] a;
FileInputStream in=
new FileInputStream(new File(inputFilePath));
byte[] b=new byte[in.available()];
in.read(b);
a=new String(b).toCharArray();
return a;
}
static void fileWrite(String outputFilePath) throws IOException{
FileOutputStream o=
new FileOutputStream (new File(outputFilePath));
o.write(ostr.toString().getBytes());
}
static void translate(char[] data){
String s;
for(int i=0;i<data.length;i++){
s="";
switch(data[i]){
case '+':s="(*ptr)++;";break;
case '-':s="(*ptr)--;";break;
case '>':s="ptr++;";break;
case '<':s="ptr--;";break;
case '.':s="putchar(*ptr);";break;
case ',':s="*ptr=getchar();";break;
case '[':s="\n while(*ptr){";break;
case ']':s="}\n";break;
}
ostr.append(s);
}
ostr.append("return 0;\n}");
}
public static void main(String[] args){
try{
ostr=new StringBuffer();
char[] c=fileRead(args[0]);
ostr.append("#include <stdio.h>\n");
ostr.append("int main(){\n");
ostr.append("char mem[65536];");
ostr.append("char *ptr=mem;");
translate(c);
fileWrite(args[0]+".c");
}catch(IOException e){}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment