1 /* vi: set sw=4 ts=4: */
10 /* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */
12 static double stack[100];
13 static unsigned int pointer;
14 static unsigned char base;
16 static void push(double a)
18 if (pointer >= (sizeof(stack) / sizeof(*stack)))
19 bb_error_msg_and_die("stack overflow");
23 static double pop(void)
26 bb_error_msg_and_die("stack underflow");
27 return stack[--pointer];
37 double subtrahend = pop();
39 push(pop() - subtrahend);
47 static void power(void)
49 double topower = pop();
51 push(pow(pop(), topower));
54 static void divide(void)
56 double divisor = pop();
58 push(pop() / divisor);
63 unsigned int d = pop();
65 push((unsigned int) pop() % d);
70 push((unsigned int) pop() & (unsigned int) pop());
75 push((unsigned int) pop() | (unsigned int) pop());
80 push((unsigned int) pop() ^ (unsigned int) pop());
85 push(~(unsigned int) pop());
88 static void set_output_base(void)
90 base=(unsigned char)pop();
91 if ((base != 10) && (base != 16)) {
92 fprintf(stderr, "Error: base = %d is not supported.\n", base);
97 static void print_base(double print)
100 printf("%x\n", (unsigned int)print);
102 printf("%g\n", print);
105 static void print_stack_no_pop(void)
107 unsigned int i=pointer;
109 print_base(stack[--i]);
112 static void print_no_pop(void)
114 print_base(stack[pointer-1]);
119 void (*function) (void);
122 static const struct op operators[] = {
142 {"f", print_stack_no_pop},
143 {"o", set_output_base},
147 static void stack_machine(const char *argument)
149 char *endPointer = 0;
151 const struct op *o = operators;
156 d = strtod(argument, &endPointer);
158 if (endPointer != argument) {
163 while (o->name != 0) {
164 if (strcmp(o->name, argument) == 0) {
170 bb_error_msg_and_die("%s: syntax error.", argument);
173 /* return pointer to next token in buffer and set *buffer to one char
174 * past the end of the above mentioned token
176 static char *get_token(char **buffer)
179 char *current = *buffer;
181 while (isspace(*current)) { current++; }
184 while (!isspace(*current) && *current != 0) { current++; }
190 /* In Perl one might say, scalar m|\s*(\S+)\s*|g */
191 static int number_of_tokens(char *buffer)
195 while (get_token(&b)) { i++; }
199 int dc_main(int argc, char **argv)
201 /* take stuff from stdin if no args are given */
207 while ((line = bb_get_chomped_line_from_file(stdin))) {
209 len = number_of_tokens(line);
210 for (i = 0; i < len; i++) {
211 token = get_token(&cursor);
213 stack_machine(token);
221 stack_machine(argv[1]);