Informatik2_Pr/zahlsys.c
2025-06-09 15:19:02 +02:00

89 lines
2.5 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
void ausgabeBinaer(int wert) {
for (int i = 31; i >= 0; i--) {
int bit = (wert >> i) & 1;
printf("%d", bit);
if (i % 8 == 0 && i != 0)
printf(" ");
}
printf("\n");
}
int main(int argc, char *argv[])
{
char eingabe[100] = {0};
for (int i = 1; i < argc; i++) {
strcat(eingabe, argv[i]);
if (i < argc - 1)
strcat(eingabe, " ");
}
char *pptr, *nptr;
char fehlerChar;
int wert, fehlerWert = 0;
bool b = false, o = false, h = false, fehler = false;
do {
if (!(strpbrk(eingabe, " -123456789")))
break;
nptr = strchr(eingabe, ' ') + 1;
pptr = strtok(eingabe, " ");
if (pptr[0] == '-' && pptr[1] == '-')
for (int i = 0; pptr[i]; ++i) {
switch (pptr[i]) {
case 'b':
b = true;
break;
case 'o':
o = true;
break;
case 'h':
h = true;
break;
case '-':
break;
default:
fehlerChar = pptr[i];
fehler = true;
break;
}
}
else if ((pptr[0] >= '0' && pptr[0] <= '9') || (pptr[0] == '-' && pptr[1] != '-')) {
if (fehlerWert == 0) {
wert = atoi(pptr);
fehlerWert++;
} else
fehler = true;
}
if (nptr != NULL + 1)
strcpy(eingabe, nptr);
} while (nptr != NULL + 1);
if (fehler == false) {
printf("Dezimal: %d\n", wert);
if (b) {
printf("Dual: ");
ausgabeBinaer(wert);
}
if (o)
printf("Oktal: %o\n", wert);
if (h)
printf("Hexadezimal: %x\n", wert);
if (b == 0 && o == 0 && h == 0) {
printf("Dual: ");
ausgabeBinaer(wert);
printf("Oktal: %o\n", wert);
printf("Hexadezimal: %x\n", wert);
}
} else if (fehler == true) {
if (fehlerChar)
printf("...... Unerlaubte Option --%c\n", fehlerChar);
if (fehlerWert == 1)
printf("usage: zahlsys [--boh] zahl\n...... Es muss genau eine Zahl angegeben sein\n");
}
}