Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

My first Brainfuck

Name: The Amazing Anus !Anus3nMVO2 2009-08-31 1:43

I was bored as fuck so I decided to implement a Brainfuck interpreter in C.

/* brainfuck.c ... version 0.9
 *
 * usage: brainfuck <file>
 *
 */

 
#include <stdio.h>

/* 64kb -1b each
 *
 * The Brainfuck spec says that memory should be 30000 bytes, but I prefer to
 * use a whole 64kb for both code and memory.
 *
 */
#define BRAINF_CODESIZE   65535
#define BRAINF_MEMSIZE   65535


FILE* fp;

unsigned char* code, *memory;
short unsigned int codeptr, memptr;


int main(int argc, char* argv[])
{
     if (argc != 2)
          exit(1);

     if ((fp = fopen(argv[1], "r")) == NULL)
          exit(1);

     code = malloc(BRAINF_CODESIZE);
     memory = malloc(BRAINF_MEMSIZE);

     memset(code, 0, BRAINF_CODESIZE);
     memset(memory, 0, BRAINF_MEMSIZE);

     codeptr = 0;
     memptr = 0;

     while (!feof(fp))
     {
          fread(code, BRAINF_CODESIZE -1, 1, fp);
     }


     /*** Interpreting begins ***/
     while (code[codeptr])
     {
          switch (code[codeptr])
          {
               case '>':
                    ++memptr;
                    ++codeptr;
                    break;

               case '<':
                    --memptr;
                    ++codeptr;
                    break;

               case '+':
                    ++memory[memptr];
                    ++codeptr;
                    break;

               case '-':
                    --memory[memptr];
                    ++codeptr;
                    break;

               case '.':
                    putchar(memory[memptr]);
                    ++codeptr;
                    break;

               case ',':
                    memory[memptr] = getchar();
                    ++codeptr;
                    break;

               /* :NOTE: Some kind of error handling should take
                * place if no ']' is found.
                */
               case '[':
                    if (!memory[memptr])
                    {
                         while ((code[codeptr] != ']') && (code[codeptr]))
                         {
                              ++codeptr;
                         }
                    }
                    else
                         ++codeptr;
                    break;


               /* :NOTE: Some kind of error handling should take
                * place if no '[' is found.
                */
               case ']':
                    if (memory[memptr])
                    {
                         while ((code[codeptr] != '[') && (codeptr))
                              --codeptr;
                    }
                    else
                         ++codeptr;
                    break;

               /* invalid instruction
                * For now we will just continue executing when this happens.
                * It should ignore characters 10, 13, & 32 anyways.
                */
               default:
                    ++codeptr;
                    break;
          }
     }

     free(code);
}

Name: Anonymous 2009-09-03 12:21

>>36

Fine.  Go improve mine by improving load time optimization:  put in an array of numbers to tell you how many times each symbol appears in a row.  Like +++>>----< would in memory be:

source: +>-<
number: 3241

Then just += number[i] instead of repeated ++



By the way, anon < http://code.google.com/p/awib/source/browse/builds/awib-1.0rc6-BETA.b

Name: Anonymous 2009-09-03 12:34

>>41
If you're going for load time optimization, you can speed up the loops even more if, instead of using a stack, determine during load time which address to jump to for each [ and ] instruction.

Name: The Amazing Anus !Anus3nMVO2 2009-09-03 14:44

All times are averages after several runs.

$ time bf bench.bf
real    0.649 secs

$ time qdbf bench.bf
real    0.220 secs

$ time bfanon34 bench.bf
real    0.186 secs


Ok, it seems that I can't do anything to get >>38-chan's interpreter to accept my bench.bf program.  It also hangs forever if I try to run the quine on it... same with the program that prints the Fibonacci numbers.

The only thing that actually works is "Hello, World!"  I get corrupted stack and segmentation fault when I try to run the Fibonacci program on it.  I'll see if I can find out what its problem is.

Name: Anusymous 2009-09-03 15:30

>>43
You're an anus!

Name: The Amazing Anus !Anus3nMVO2 2009-09-03 15:35

>>44
I big anus that can talk and feel.

Name: Anonymous 2009-09-03 15:54

>>45
No question mark = imposter.

Name: Anonymous 2009-09-03 16:32

>>45
* I big anus that can talk, and feel?

Name: !Anusribs4k 2009-09-03 16:52

>>47
TYPO FUCK SAKE!!!!

Name: Anonymous 2009-09-03 20:26

>>48
Typographical errors

Here are some typographical errors, spotted by various readers. Page numbers refer to the online versions (which differ from the printed version).
• Page 128, second to last paragraph of section 3.7, first sentence. "addis" should be "is a".
• Page 134, the code for i'. The "n" under the big brace symbol should say "n pairs".
• Page 135. Equation 3.36 should have "NConstr", not "Constr".
• Page 230, second paragraph. "There one final gloss..." should be "There is one final gloss...".
• Page 278, the definition of nfib. Replace "n==0" by "n<=1".

Name: Anonymous 2009-09-03 20:52

>>1
I can't wait until Janefuck comes out.

Name: Anonymous 2009-09-04 1:16

>>43
I didn't test it, just got it to compile (actually it compiled straight away) and checked the Hello, World program on Wikipedia. That being said it runs your fibs program fine, how are you compiling/running? If you post the line number of the segfault I'll have a look.

Name: Anonymous 2009-09-04 1:47

>>51
I compiled it with gcc -o bfanon38 bfanon38.c

Ok, now I am able to successfully run the Fibonacci thing...  But bench.bf still causes yours to hang.  I could use a better benchmarking program, but it works fine on the other 3 so I'm not sure what it is about yours.

Name: Anonymous 2009-09-04 1:52

>>52
Post bench.bf

Name: Anonymous 2009-09-04 2:10

HOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com xHOT STRIPPING COEDS http://twentyfirstcenturycoeds.comicgenesis.com x

Name: Anonymous 2009-09-04 2:28

>>54
how the hell did this get past the autoban?

Name: Anonymous 2009-09-04 4:47

>>55
YHBT.

Name: Anonymous 2009-09-04 5:25

>>55
No autoban on the text boards- duh.

Name: Anonymous 2009-09-04 5:53

>>57
yes there is... or was.
i remember several times in which i have been banned because evidently i am a spambot. each time it happened i was posting four or five urls in the same post, so i just put two and two together.

Name: Anonymous 2009-09-04 6:33

There is an autobanner and it's apparently broken. I was deemed a spambot when I was making a regular posts. No URLs, no repetition.

Name: Anonymous 2009-09-04 13:49

>>58-59
Did you get a popup saying "spam.html" ?

Name: Anonymous 2009-09-04 13:51

>>60
Almost; I got an offer from Firefox to save a file with such name.

Name: Anonymous 2009-09-04 17:56

I think that bfanon38 hanging is something to do with not supporting cell wrap-around.  Working on a better bench.bf at the moment 'cause the last one is shit.

Name: Anonymous 2009-10-29 14:27

Bampu pantsu

Name: GNU pig disgusting 2009-10-29 20:45

I approve of the indentation used in this thread.

Name: Anonymous 2009-10-29 23:35

>>65
Oh holy fuck, I hadn't noticed until now.

Name: Anonymous 2009-10-30 13:02

>>43
The time given under "user" is a far better description of how fast a program runs than "real". Anyway, If you want fast, try beef or the program that beef stole its code from. It matches brackets while the code is loading by loading it into a binary tree. Run-time bracket matching is slower.

Name: Anonymous 2009-11-14 9:41

Why do people write brainfuck interpreters? The thing is so simple that you can write brainfuck in brainfuck. If you're using C, compile the damn code already

Name: Anonymous 2009-11-14 9:50

>>68
Well, why not?

how do i emitted compiled code???

Name: Anonymous 2009-11-14 9:58

>>68
There has been more than one brainfuck compiler posted, It's probably personal preference

Name: Anonymous 2009-11-14 10:30

>>68
C++ is so simple that you can write C++ in C++.

Name: Anonymous 2009-11-14 11:03

                       //`'''```,
             o        // LISP   `.,
       ,....OOo.   .c;.',,,.'``.,,.`
    .'      ____.,'.//
   / _____  \___/.'
  | / ||  \\---\|
  ||  ||   \\  ||
  co  co    co co

Name: Anonymous 2009-11-15 19:06

#include <iostream>

using std::cin;
using std::cout;
using std::cerr;
using std::endl;
#define MS (65536)
struct state {
        unsigned char * tape;
        size_t head;
        static state s;
private:
        state() : tape(new unsigned char[MS]), head() {}
};
state state::s;
state & s = state::s;

template <char c, int times = 1>
struct insn {
        enum { C = c };
        enum { T = 0 };
        void operator () () const {}
};

template <typename B, typename I>
struct block : B {
        typedef B base;
        typedef I insn_;

        block() {}
        block(B const &, I const &) {}

        void operator () () const { B::operator () (); I()(); }

        block<B, insn<I::C, I::T + 1>> operator , (insn<I::C, 1> const &)
        { return block<B, insn<I::C, I::T + 1>>(); }

        template <char c>
        block<block<B, I>, insn<c>> operator , (insn<c> const & i2)
        { return block<block<B, I>, insn<c>>(*this, i2); }
};

template <>
struct block<void, void> {
        typedef void insn_;

        void operator () () const { }

        template <char c>
        block<block, insn<c>> operator , (insn<c> const & i) { return block<block, insn<c>>(*this, i); }
        static block BF;
        block(block const &) {}
        block() {}
};
block<void, void> block<void, void>::BF;
block<void, void> & BF = block<void, void>::BF;

template <typename B>
struct block<B, insn<'['>> : block<void, void> {
        typedef insn<'['> insn_;

        typedef B prev_block;

        block() {}
        block(B const &, insn<'['> const &) {}

        void operator () () const { }

        template <char c>
        block<block<B, insn<'['>>, insn<c>> operator , (insn<c> const & i2)
        { return block<block<B, insn<'['>>, insn<c>>(*this, i2); }
};

template <typename B>
struct block<B, insn<']'>> : B::prev_block {
        typedef insn<']'> insn_;

        block() {}
        block(B const &, insn<']'> const &) {}

        void operator () () const {
                B::prev_block::operator () ();
                while (s.tape[s.head])
                { B()(); }
        }

        template <char c>
        block<block<B, insn<']'>>, insn<c>> operator , (insn<c> const & i2)
        { return block<block<B, insn<']'>>, insn<c>>(*this, i2); }
};

template <int times>
struct insn<'<', times> {
        static char const C = '<';
        static int const T = times;
        void operator () () const {
                if (s.head >= times) s.head -= times;
                else s.head = 0;
        }
};

template <int times>
struct insn<'>', times> {
        static char const C = '>';
        static int const T = times;
        void operator () () const {
                if (s.head + times < MS) s.head += times;
                else s.head = MS - 1;
        }
};

template <int times>
struct insn<'-', times> {
        static char const C = '-';
        static int const T = times;
        void operator () () const {
                s.tape[s.head] -= times;
        }
};

template <int times>
struct insn<'+', times> {
        static char const C = '+';
        static int const T = times;
        void operator () () const {
                s.tape[s.head] += times;
        }
};

template <int times>
struct insn<'.', times> {
        static char const C = '.';
        static int const T = times;
void dump(unsigned char c) const
{
        static int dotc = 155;

        if (dotc-- == 0) { cerr << "too much output" << endl; exit(1); }

        if (c == ' ' || c == '\n' || (c >= 'A' && c <= 'z')) cout << c;
        //else cout << "ip: " << ip << " head: " << head << " depth: " << depth << ' ' << (int)c << endl;
        else cout << (int)c;
}

        void operator () () const {
                for (int i = 0; i < times; i++) dump(s.tape[s.head]);
        }
};

template <int times>
struct insn<',', times> {
        static char const C = ',';
        static int const T = times;
        void operator () () const {
                for (int i = 0; i < times; i++) cin >> s.tape[s.head];
        }
};

template <int times>
struct insn<'[', times> {
        static_assert(times == 1, "No merged loops.");
        static char const C = '[';
        static int const T = times;
        void operator () () const {
        }
};

template <int times>
struct insn<']', times> {
        static_assert(times == 1, "No merged loops.");
        static char const C = ']';
        static int const T = times;
        void operator () () const {
        }
};

        insn<'<'> l;
        insn<'>'> r;
        insn<'+'> p;
        insn<'-'> m;
        insn<'.'> d;
        insn<','> c;
        insn<'['> b;
        insn<']'> e;
int main()
{
        auto prog = (BF
                        BFCODE
        );
        prog();
}


I used sepples C++1x:
g++ -std=c++0x -DBFCODE=`cat x.bf` bf.C -o x

This generates the BFCODE from .bf:
tr -d -c '<>+\-.,[]' | tr '<>+\-.,[]' lrpmdcbe | perl -pe 's/(.)/,$1/g'

Tested with this:
[url]https://trac.parrot.org/languages/browser/bf/trunk/bench.bf[/url]. It takes a little time to compile, but it runs under a second.

Name: Anonymous 2009-11-15 19:32

>>73
Goodness!!  It sure is good to know that what I can do in 88 lines of C can be done in a slim 159 lines of C++

Praise Sepples!

Name: Anonymous 2009-11-15 19:35

Also, I never really did get around to writing a decent Brainfuck benchmarker.

Anyone up to the task?

Name: Anonymous 2009-11-15 20:11

>>75
alias brainfuck_benchmarker=time

Name: Anonymous 2009-11-15 21:21

>>73
I LOVE YOU! I LOVE YOUR POST! I READ IT 5 TIMES! KEEP POSTING!

Name: Anonymous 2009-11-15 21:32

Next challenge: implement a Brainfuck processor in hardware.

Name: Anonymous 2009-11-15 22:11

>>73
This is actually really impressive.

Name: Haxus the Error Report 2009-11-15 22:23

>>73
C:\Dev-Cpp\projects\bfpp.cpp:35: error: a function call cannot appear in a constant-expression

C:\Dev-Cpp\projects\bfpp.cpp:36: error: missing `>' to terminate the template argument list

C:\Dev-Cpp\projects\bfpp.cpp:36: error: missing `>' to terminate the template argument list

C:\Dev-Cpp\projects\bfpp.cpp:36: error: template argument 2 is invalid

C:\Dev-Cpp\projects\bfpp.cpp:36: error: expected unqualified-id before '{' token

C:\Dev-Cpp\projects\bfpp.cpp:39: error: `>>' should be `> >' within a nested template argument list

C:\Dev-Cpp\projects\bfpp.cpp: In member function `block<block<B, I>, insn<c, 1> > block<B, I>::operator,(const insn<c, 1>&)':
C:\Dev-Cpp\projects\bfpp.cpp:40: error: `>>' should be `> >' within a nested template argument list

C:\Dev-Cpp\projects\bfpp.cpp: At global scope:

C:\Dev-Cpp\projects\bfpp.cpp:50: error: `>>' should be `> >' within a nested template argument list

C:\Dev-Cpp\projects\bfpp.cpp: In member function `block<block<void, void>, insn<c, 1> > block<void, void>::operator,(const insn<c, 1>&)':
C:\Dev-Cpp\projects\bfpp.cpp:50: error: `>>' should be `> >' within a nested template argument list

C:\Dev-Cpp\projects\bfpp.cpp: At global scope:

C:\Dev-Cpp\projects\bfpp.cpp:59: error: missing `>' to terminate the template argument list

C:\Dev-Cpp\projects\bfpp.cpp:59: error: template argument 1 is invalid

C:\Dev-Cpp\projects\bfpp.cpp:59: error: missing `>' to terminate the template argument list

C:\Dev-Cpp\projects\bfpp.cpp:59: error: template argument 2 is invalid

C:\Dev-Cpp\projects\bfpp.cpp:75: error: missing `>' to terminate the template argument list

C:\Dev-Cpp\projects\bfpp.cpp:75: error: template argument 1 is invalid

C:\Dev-Cpp\projects\bfpp.cpp:75: error: missing `>' to terminate the template argument list

C:\Dev-Cpp\projects\bfpp.cpp:75: error: template argument 2 is invalid

C:\Dev-Cpp\projects\bfpp.cpp:161: error: ISO C++ forbids declaration of `static_assert' with no type

C:\Dev-Cpp\projects\bfpp.cpp:161: error: expected `;' before '(' token

C:\Dev-Cpp\projects\bfpp.cpp:170: error: ISO C++ forbids declaration of `static_assert' with no type

C:\Dev-Cpp\projects\bfpp.cpp:170: error: expected `;' before '(' token

C:\Dev-Cpp\projects\bfpp.cpp: In function `int main()':
C:\Dev-Cpp\projects\bfpp.cpp:187: error: ISO C++ forbids declaration of `prog' with no type

C:\Dev-Cpp\projects\bfpp.cpp:188: error: expected `)' before "BFCODE"

C:\Dev-Cpp\projects\bfpp.cpp:189: error: cannot convert `block<void, void>' to `int' in initialization

C:\Dev-Cpp\projects\bfpp.cpp:190: error: `prog' cannot be used as a function

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List