1 /* vi: set sw=4 ts=4: */
8 /* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */
10 static const char math_usage[] = "math expression ...\n"
11 #ifndef BB_FEATURE_TRIVIAL_HELP
12 "\nThis is a Tiny RPN calculator that understands the\n"
13 "following operations: +, -, /, *, and, or, not, eor.\n"
14 "i.e. 'math 2 2 add' -> 4, and 'math 8 8 \\* 2 2 + /' -> 16\n"
18 static double stack[100];
19 static unsigned int pointer;
21 static void push(double a)
23 if (pointer >= (sizeof(stack) / sizeof(*stack))) {
24 fprintf(stderr, "math: stack overflow\n");
33 fprintf(stderr, "math: stack underflow\n");
36 return stack[--pointer];
46 double subtrahend = pop();
48 push(pop() - subtrahend);
58 double divisor = pop();
60 push(pop() / divisor);
65 push((unsigned int) pop() & (unsigned int) pop());
70 push((unsigned int) pop() | (unsigned int) pop());
75 push((unsigned int) pop() ^ (unsigned int) pop());
80 push(~(unsigned int) pop());
85 printf("%g\n", pop());
93 static const struct op operators[] = {
105 static void stack_machine(const char *argument)
107 char *endPointer = 0;
109 const struct op *o = operators;
116 d = strtod(argument, &endPointer);
118 if (endPointer != argument) {
123 while (o->name != 0) {
124 if (strcmp(o->name, argument) == 0) {
130 fprintf(stderr, "math: %s: syntax error.\n", argument);
134 int math_main(int argc, char **argv)
136 if (argc <= 1 || *argv[1]=='-')
139 stack_machine(argv[1]);