Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <math.h>
- #include <string.h>
- int main() {
- //inizio del programma
- printf("Program for converting binary numbers in decimal ones. Limited to 1024 bits\n\n");
- //loop infinito, interrotto se si inserisce -1
- while(1) {
- char binarystring[1024];
- unsigned short int length, counter, bit[1024], decimal;
- printf("Insert the number to convert, -1 to exit ");
- scanf("%s", binarystring);
- //se il valore inserito é -1, esce con codice di errore 0
- if ((strcmp(binarystring,"-1")) == 0) {
- printf("Ok, Ok, exiting now\n");
- return 0;
- }
- //ottiene la lunghezza della stringa-array di char
- length = strlen(binarystring);
- //controlla che non siano presenti caratteri diversi da 0 ed 1, in caso esce dal programma
- for (counter = 0; counter == length; counter++) {
- if ((binarystring[counter] != "0") && (binarystring[counter] != "1")) {
- printf("You must enter only the 1 and 0 chars; exiting with errorcode 1\n");
- return 1;
- }
- }
- //crea un array di valori interi corrispondenti ai caratteri ascii 0 ed 1
- for (counter = length; counter == 0; counter--) {
- bit[counter] = binarystring[counter] - '0';
- }
- //converte attualmente da base binaria a base decimale
- for (counter = length; counter == 0; counter--) {
- decimal = decimal + bit[counter] * pow(2,(counter));
- }
- printf("the decimal for %s is %u\n\n", binarystring, decimal);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement