Skip to content

Instantly share code, notes, and snippets.

@kodejuice
Last active September 1, 2022 14:45
Show Gist options
  • Select an option

  • Save kodejuice/77eee56c2ea5f983d4be3e2480d695eb to your computer and use it in GitHub Desktop.

Select an option

Save kodejuice/77eee56c2ea5f983d4be3e2480d695eb to your computer and use it in GitHub Desktop.

Revisions

  1. kodejuice revised this gist Jul 30, 2018. No changes.
  2. kodejuice revised this gist Jul 30, 2018. No changes.
  3. kodejuice created this gist Aug 27, 2017.
    42 changes: 42 additions & 0 deletions brainfuck.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@

    char * brain_fuck(char * code, char * input){
    const int BUFSIZE = 30000;
    int * ptr = (int *) malloc(BUFSIZE * sizeof(int)),
    i_sz = strlen(input), c_sz = strlen(code),
    idx = -1, j = 0, o = 0;
    char cmd, * output = (char *) malloc(BUFSIZE);

    while (idx++ < c_sz){
    cmd = code[idx];
    if (cmd == '.' && *ptr > 0 && *ptr < 256) output[o++] = (char) *ptr;
    else if (cmd == '+') *ptr = ((*ptr | 0) + 1) % 256;
    else if (cmd == '-') *ptr = ((*ptr | 0) - 1), *ptr = *ptr == -1 ? 255 : *ptr;
    else if (cmd == '>') ptr++;
    else if (cmd == '<') ptr--;
    else if (cmd == ',' && j < i_sz) *ptr = input[j++];
    else if (cmd == '['){
    int open = 1, i = idx + 1;
    *ptr = (*ptr | 0);
    if (!*ptr){
    while (open && i++ < c_sz)
    if (code[i-1] == '[') open += 1;
    else if(code[i-1] == ']') open -= 1;
    idx = i - 1;
    }
    }
    else if (cmd == ']'){
    int open = 1, i = idx - 1;
    *ptr = (*ptr | 0);
    if (*ptr){
    while (open && i-- >= 0)
    if (code[i+1] == '[') open -= 1;
    else if (code[i+1] == ']') open += 1;
    idx = i + 1;
    }
    }
    }
    output[o] = '\0';
    return output;
    }

    brain_fuck(",[.>,]", "hello"); //=> "hello"