Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Copyright © 2010, Martin Brandenburg
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define BUF_SPACE 1024
- int main (int argc, char const *argv[])
- {
- unsigned char buf[BUF_SPACE] = {0};
- unsigned int ptr = 0;
- char *input = "+++>++<[->>+<<]>[->+<]>++++++++++++++++++++++++++++++++++++++++++++++++."
- "[-]++++++++++.";
- unsigned int iptr = 0;
- unsigned int loopstart = 0, loopend = 0;
- int i;
- for (iptr = 0; iptr <= strlen(input); iptr++) {
- switch (input[iptr]) {
- case '<':
- ptr--;
- if ((ptr >= BUF_SPACE) || (ptr < 0)) {
- /* something more intelligent could be done here, like expanding the buffer */
- fprintf(stderr, "error: not enough memory\n");
- fprintf(stderr, "error: ptr was %#x\n", ptr);
- exit(-1);
- }
- break;
- case '>':
- ptr++;
- if ((ptr >= BUF_SPACE) || (ptr < 0)) {
- fprintf(stderr, "error: not enough memory\n");
- fprintf(stderr, "error: ptr was %#x\n", ptr);
- exit(-1);
- }
- break;
- case '-':
- buf[ptr]--;
- break;
- case '+':
- buf[ptr]++;
- break;
- case ',':
- buf[ptr] = getchar();
- break;
- case '.':
- putchar(buf[ptr]);
- break;
- case '[':
- /* subtract 1 so we start at this check code */
- loopstart = iptr-1;
- loopend = strchr(input+iptr, ']') - input;
- if (buf[ptr] == 0) {
- iptr = loopend;
- continue;
- }
- break;
- case ']':
- iptr = loopstart;
- continue;
- default:
- break;
- }
- #ifdef DEBUG
- /* dump the machine's state */
- printf("Iteration:\n");
- printf("Loopstart: %u, loopend: %u\n", loopstart, loopend);
- printf("Ptr: %u, iptr: %u\n", ptr, iptr);
- printf("Memory: [");
- for (i = 0; i < 20; i++) {
- printf("%02d,", buf[i]);
- }
- printf("]\n\n");
- #endif
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment