/* bittilaskin Peruslaskutoimitukset ja bittioperaatiot etumerkittömillä binääri-, oktaali-, desimaali- ja heksadesimaaliluvuilla. Tunnetut laskutoimitukset: b..., 0b... = binääri o..., 0o..., 0[0-7]... = oktaali x..., 0x... = heksadesimaali d..., 0d..., [1-9]... = desimaali Kerralla (yhdellä rivillä) joko laskutoimituksen ensimmäinen argumentti tai laskutoimitus ja (tarvittaessa) toinen argumentti. Tunnetut laskutoimitukset C:n notaatiolla: + - * / ~ & | ^ << >> Argumenttina voidaan antaa haluttu bittimäärä (max 32, oletus 16). */ #include #include #include #include "numscan.h" #define MAXROW 80 #define BITS 16 int main(int argc, char *argv[]) { unsigned long x=0, y; int bits = 16; int mask; char row[MAXROW]; if (argc>1) sscanf(argv[1],"%d",&bits); if (bits>32 || bits <2) { fprintf(stderr, "invalid bit count %d\n", bits); exit(1); } printf("Using %d bits\n", bits); printf("Ctrl-d or q to quit\n"); mask = ~(~0 << bits); while (1) { printf("? "); if (NULL==fgets(row, MAXROW, stdin)) exit(EXIT_SUCCESS); switch(row[0]) { case '\n': break; case 'q': exit(EXIT_SUCCESS); case '~': x = ~x; break; case '&': y = numscan(row+1); x = x & y; break; case '|': y = numscan(row+1); x = x | y; break; case '^': y = numscan(row+1); x = x ^ y; break; case '+': y = numscan(row+1); x = x + y; break; case '-': y = numscan(row+1); x = x - y; break; case '*': y = numscan(row+1); x = x * y; break; case '/': y = numscan(row+1); x = x / y; break; case '<': if(row[1] == '<') { y = numscan(row+2); x = x << y; break; } else { fprintf(stderr, "syntax error\n"); break; } case '>': if(row[1] == '>') { y = numscan(row+2); x = x >> y; break; } else { fprintf(stderr, "syntax error\n"); break; } case 'd': case 'o': case 'x': case 'b': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': x = numscan(row); break; default: fprintf(stderr, "syntax error\n"); continue; } x &= mask; printf("b"); printbin(x, bits); printf(", o%lo, d%lu, x%lx\n", (long) x, (long) x, (long)x); } return 0; }