-
-
Save spacelatte/99d0d3f74a70a8eabb72993a92dda0a2 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in bash
This file contains hidden or 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
#! /bin/bash | |
CELLS=500 | |
buffer=() | |
stack=() | |
ap=0 | |
for i in {1..$CELLS}; do | |
buffer+=(0) | |
done | |
read -r -d '!' code | |
echo | |
for ((ip = 0; ip < ${#code}; ip++ )); do | |
op=${code:$ip:1} | |
case "$op" in | |
'[') | |
if [[ ${buffer[$ap]} == 0 ]]; then | |
depth=1 | |
while [[ $depth > 0 ]]; do | |
((ip++)) | |
op=${code:$ip:1} | |
if [[ "$op" == '[' ]]; then | |
((depth++)) | |
elif [[ "$op" == ']' ]]; then | |
((depth--)) | |
fi | |
done | |
else | |
stack+=($ip) | |
fi | |
;; | |
']') | |
if [[ ${buffer[$ap]} != 0 ]]; then | |
((ip = stack[${#stack[@]}-1])) | |
else | |
unset stack[${#stack[@]}-1] | |
fi | |
;; | |
'>') ((ap=(ap+1) % CELLS)) ;; | |
'<') ((ap=(ap==0) ? CELLS-1 : ap-1)) ;; | |
'+') ((buffer[ap]=(buffer[ap]+1) % 256)) ;; | |
'-') ((buffer[ap]=(buffer[ap]==0) ? 255 : buffer[ap]-1)) ;; | |
'.') printf "\x$(printf %x ${buffer[$ap]})" ;; | |
',') buffer[$ap]=$(printf "%d" "'$(read -n 1)") ;; | |
esac | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment