int main(void) { char bst[CHAR_BIT*sizeof(int)+1] = {0}; printf("Enter a binary string: "); while(scanf("%s", bst)==1){ printf("Binary \"%s\" is %d in decimal notation.\n", bst, abtoi(bst)); printf("\nPlease enter another binary string (EOF to quit): "); } return 0; }
/* * recursive expression parser * * Input: pointer to argument rest string * * Output: computed value */ int eval(char *s) { register char *p; register int val; char word[MAXLINE]; struct sym *sp; val = 0; while (*s) { p = word; if (*s == '(') { s++; while (*s != ')') { if (*s == '\0') { asmerr(E_MISPAR); goto eval_break; } *p++ = *s++; } *p = '\0'; s++; val = eval(word); continue; } if (*s == STRSEP) { s++; while (*s != STRSEP) { if (*s == '\n' || *s == '\0') { asmerr(E_MISHYP); goto hyp_error; } *p++ = *s++; } s++; hyp_error: *p = '\0'; val = strval(word); continue; } if (isari(*s)) *p++ = *s++; else while (!isspace(*s) && !isari(*s) && (*s != '\0')) *p++ = *s++; *p = '\0'; switch (get_type(word)) { case OPESYM: /* symbol */ if (strcmp(word, "$") == 0) { val = pc; break; } if (strlen(word) > SYMSIZE) word[SYMSIZE] = '\0'; if ((sp = get_sym(word)) != NULL) val = sp->sym_val; else asmerr(E_UNDSYM); break; case OPEDEC: /* decimal number */ val = atoi(word); break; case OPEHEX: /* hexadecimal number */ val = axtoi(word); break; case OPEBIN: /* binary number */ val = abtoi(word); break; case OPEOCT: /* octal number */ val = aotoi(word); break; case OPESUB: /* arithmetical - */ val -= eval(s); goto eval_break; case OPEADD: /* arithmetical + */ val += eval(s); goto eval_break; case OPEMUL: /* arithmetical * */ val *= eval(s); goto eval_break; case OPEDIV: /* arithmetical / */ val /= eval(s); goto eval_break; case OPEMOD: /* arithmetical modulo */ val %= eval(s); goto eval_break; case OPESHL: /* logical shift left */ val <<= eval(s); goto eval_break; case OPESHR: /* logical shift right */ val >>= eval(s); goto eval_break; case OPELOR: /* logical OR */ val |= eval(s); goto eval_break; case OPELAN: /* logical AND */ val &= eval(s); goto eval_break; case OPEXOR: /* logical XOR */ val ^= eval(s); goto eval_break; case OPECOM: /* logical complement */ val = ~(eval(s)); goto eval_break; } } eval_break: return(val); }