Skip to content

Instantly share code, notes, and snippets.

@Earlz
Created November 15, 2017 01:41
Show Gist options
  • Save Earlz/27b8130426e1d36e55446e32e7770fb9 to your computer and use it in GitHub Desktop.
Save Earlz/27b8130426e1d36e55446e32e7770fb9 to your computer and use it in GitHub Desktop.
//compiles to 740 bytes using -O0, 384 bytes using -Os
//both targeting i386 and with freestanding GCC compiler
typedef unsigned int size_t;
void interpret(volatile char* s, int s_size, volatile char* input, volatile char* output){
int i=0;
int right = s_size;
size_t ptr;
int BUFSIZE = 1000;
char buf[BUFSIZE];
int inpos=0;
int outpos=0;
while ( i < right){
switch(s[i]){
case '>':
{
ptr++;
if(ptr >= BUFSIZE){
ptr = 0;
}
break;
}
case '<':
{
ptr--;
if(ptr < 0){
ptr = BUFSIZE - 1;
}
break;
}
case '.':
buf[ptr] = input[inpos];
inpos++;
break;
case '+':
buf[ptr]++;
break;
case '-':
buf[ptr]--;
break;
case '[':
{
int loop = 1;
while(loop > 0){
i++;
char c = s[i];
if(c == '['){
loop++;
}else if(c == ']'){
loop--;
}
}
break;
}
case ']':
{
int loop = 1;
while(loop > 0){
i--;
char c = s[i];
if(c == '['){
loop--;
}else if(c == ']'){
loop++;
}
}
i--;
break;
}
case ',':
output[outpos] = buf[ptr];
outpos++;
break;
}
i++;
}
}
void start() __attribute__((section(".text.start")));
void start(){
//use volatile pointers here so the compiler doesn't assume the memory is empty
start((volatile char*)0x1000, 1000, (volatile char*)0x2000, (volatile char*)0x3000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment