Last active
December 11, 2015 20:59
-
-
Save JimmyFrix/4659352 to your computer and use it in GitHub Desktop.
A brainfuck interpreter written in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"os" | |
) | |
func interpret(instructions []byte) { | |
memory := make([]uint8, 30000) | |
pointer := 0 | |
for index := 0; index < len(instructions); index++ { | |
switch instructions[index] { | |
case '>': | |
pointer++ | |
case '<': | |
pointer-- | |
case '+': | |
memory[pointer]++ | |
case '-': | |
memory[pointer]-- | |
case '.': | |
fmt.Printf("%c", memory[pointer]) | |
case ',': | |
read := make([]byte, 1) | |
os.Stdin.Read(read) | |
memory[pointer] = read[0] | |
case '[': | |
if memory[pointer] == 0 { | |
for depth := 1; depth > 0; { | |
index++ | |
if instructions[index] == '[' { | |
depth++ | |
} else if instructions[index] == ']' { | |
depth-- | |
} | |
} | |
} | |
case ']': | |
if memory[pointer] != 0 { | |
for depth := 1; depth > 0; { | |
index-- | |
if instructions[index] == ']' { | |
depth++ | |
} else if instructions[index] == '[' { | |
depth-- | |
} | |
} | |
} | |
} | |
} | |
} | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Printf("No brainfuck file supplied\n") | |
return | |
} | |
instructions, err := ioutil.ReadFile(os.Args[1]) | |
if (err != nil) { | |
fmt.Printf("Error reading file: %v", err.Error()) | |
return | |
} | |
interpret(instructions) | |
fmt.Printf("\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment