0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Brainfuck interpreter in C and Go

Last updated at Posted at 2024-02-09

bf.c
brainfuckのインタープリタです。
cc bf.c -o bfとしてコンパイルしてください。
bf <file>とすると、ファイルからbrainfuckで書かれたプログラムを読み込み、実行します。

bf.c
#include    <stdio.h>
#include    <stdlib.h>
void main(int argc,char *argv[]) {
    FILE *fp;
    char prog[65536]={0},array[30000]={0},*ptr=array;
    int  loopstack[1000],lsp=0,idx,len;

    fp=fopen(argv[1],"rt");
    for(len=0; (prog[len]=fgetc(fp))!=EOF;len++);
    fclose(fp);

    for(idx=0;idx<len;)
        switch (prog[idx++]) {
            case '>': ptr++; continue;
            case '<': ptr--; continue;
            case '+': (*ptr)++; continue;
            case '-': (*ptr)--; continue;
            case '.': putchar(*ptr); continue;
            case ',': *ptr=getchar(); continue;
            case '[':
                if (*ptr) loopstack[lsp++]=idx-1;
                else for(int nest=1;idx<len;) {
                        int c=prog[idx++];
                        if (c=='[') nest++;
                        else if (c==']' && --nest==0) break;
                        }
                continue;
            case ']': idx=loopstack[--lsp]; continue;
            default: continue;
            }
}

Go

こちらは、goによるbrainfuckインタプリタです。
cで書いたものをGoogle AI studioでgoに変換し、手直しをしました。

hot to execute: go run bf.go sample.bf

bf.go
package main

import (
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: go run bf.go <filename>")
		return
	}

	filename := os.Args[1]
	program, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Println("Error reading file:", err)
		return
	}

	array := make([]byte, 30000)
	ptr := 0
	loopStack := make([]int, 1000)
	lsp := 0

    ip := 0

	for ip < len(program) {
        c:=program[ip]
        ip++
		switch c {
		case '>':
			ptr++
		case '<':
			ptr--
		case '+':
			array[ptr]++
		case '-':
			array[ptr]--
		case '.':
			fmt.Print(string(array[ptr]))
		case ',':
			var input byte
			fmt.Scanf("%c", &input)
			array[ptr] = input
		case '[':
			if array[ptr] != 0 {
				loopStack[lsp] = ip-1
				lsp++
			} else {
                nest := 1
                for ip < len(program) {
                    c:=program[ip]
                    ip++
					if c == '[' {
						nest++
					} else if c == ']' {
						nest--
						if nest == 0 {
							break
						}
					}
				}
			}
		case ']':
			lsp--
			ip = loopStack[lsp]
		}

		// Bounds check for the pointer. Exit with an error if out of bounds.
		if ptr < 0 || ptr >= len(array) {
			fmt.Println("Pointer out of bounds")
			return
		}
	}
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?