Skip to content

Instantly share code, notes, and snippets.

@aziascreations
Last active January 18, 2017 21:15
Show Gist options
  • Save aziascreations/fcff66f449ec806c5c701d7190cffb9b to your computer and use it in GitHub Desktop.
Save aziascreations/fcff66f449ec806c5c701d7190cffb9b to your computer and use it in GitHub Desktop.
A basic Brainfuck interpretor in java.
package com.azias.test.brainfuckio;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class BrainfuckIO {
//public static byte[] cells; //Values cells
public static int[] cells; //Values cells
public static char[] instructions; //BF code
public static int ip = 0; //InstructionPointer
public static int sp = 0; //StackPointer
public static void main(String[] args) throws IOException {
cells = new int[255];
interpret(fileToString("./scripts/BaconIpsum.bf"), 0);
//interpret(fileToString("./scripts/HelloWorld.bf"), 0);
System.out.print("\n");
//Clean
if(ip >= instructions.length) {
instructions = null;
}
}
public static void interpret(String bf, int startingPoint) {
if(instructions == null) {
if(bf != null && !bf.isEmpty()) {
instructions = bf.toCharArray();
} else {
System.exit(1);
}
}
while(ip < instructions.length) {
if(instructions[ip] == '>') {
sp++;
} else if(instructions[ip] == '<') {
sp--;
} else if(instructions[ip] == '+') {
if(cells[sp] < 255)
cells[sp]++;
else
cells[sp] = 0;
} else if(instructions[ip] == '-') {
if(cells[sp] > 0)
cells[sp]--;
else
cells[sp] = 255;
} else if(instructions[ip] == '.') {
System.out.print((char) cells[sp]);
} else if(instructions[ip] == ',') {
//System.out.println("In /");
} else if(instructions[ip] == '[') {
if(cells[sp] > 0) {
ip++;
interpret(bf, ip);
} else {
int tmpip = 1;
while(true) {
ip++;
if(instructions[ip] == '[') {
tmpip++;
} else if(instructions[ip] == ']') {
tmpip--;
if(tmpip == 0) {
break;
}
}
}
}
} else if(instructions[ip] == ']') {
ip = startingPoint - 2;
break;
}
ip++;
}
}
private static String fileToString(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment