I'm writing a C program that reads a pure binary number from the keyboard in the form of a string of characters (0 and 1) up to 24 bits long. the program must:
- Check that the inserted string is correct, that is, it is composed only of 0 and 1
- Convert bin to dec
- Print the dec
#include <stdio.h>
#define MAXC 24
int main(void)
{
char bin[MAXC + 1], dec[MAXC *2];
int i, N, j, M;
do {
printf("Enter the binary number: ");
gets(bin);
N = strlen(bin);
if (N > MAXC) {
printf("Error: max 24 bit");
}
} while (N > MAXC);
int corretto = 0;
for (i = 0; i < N; i++) {
if ((bin[i] != 0) || (bin[i] != 1)) {
corretto = 1;
}
else {
for (j = 0; j < MAXC * 2; j++) {
dec[j] = bin[i] *pow(2, N - 1 - i);
}
}
}
M = strlen(dec);
if (corretto == 1) {
printf("Il numero binario non e' scritto correttamente");
}
else {
for (j = 0; j < M; j++) {
printf("Il numero decimale e': %c", dec[j]);
}
}
return 0;
}