Info2P5/dualrech.c
2025-06-11 09:42:59 +02:00

38 lines
1.3 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int ist_dual(const char *s) {
while (*s) if (*s != '0' && *s != '1') return 0; else s++;
return 1;
}
void print_bin(int n) {
for (int i = 31; i >= 0; i--) putchar((n >> i) & 1 ? '1' : '0');
}
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Richtiger Aufruf: %s <operand> <operator> <operand>\n", argv[0]);
return 1;
}
char *a = argv[1], *op = argv[2], *b = argv[3];
int ok = 1;
if (!ist_dual(a)) { printf("....... %s ist keine erlaubte Dualzahl\n", a); ok = 0; }
if (!ist_dual(b)) { printf("....... %s ist keine erlaubte Dualzahl\n", b); ok = 0; }
if (strlen(op) != 1 || strchr("+-*/&^", op[0]) == NULL) {
printf("....... %s ist kein erlaubter Operator\n", op); ok = 0;
}
if (!ok) return 1;
int x = strtol(a, NULL, 2), y = strtol(b, NULL, 2), r = 0;
if (*op == '/' && y == 0) { printf("Fehler: Division durch 0\n"); return 1; }
switch (*op) {
case '+': r = x + y; break;
case '-': r = x - y; break;
case '*': r = x * y; break;
case '/': r = x / y; break;
case '&': r = x & y; break;
case '^': r = x ^ y; break;
}
printf("%s %s %s =\n....... ", a, op, b);
print_bin(r);
printf(" (0x%X)\n", r);
return 0;
}