Advertisement
Guest User

test

a guest
May 24th, 2012
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <string.h>
  4. int main() {
  5.     //inizio del programma
  6.     printf("Program for converting binary numbers in decimal ones. Limited to 1024 bits\n\n");
  7.     //loop infinito, interrotto se si inserisce -1
  8.     while(1) {
  9.         char binarystring[1024];
  10.         unsigned short int length, counter, bit[1024], decimal;
  11.         printf("Insert the number to convert, -1 to exit ");
  12.         scanf("%s", binarystring);
  13.         //se il valore inserito é -1, esce con codice di errore 0
  14.         if ((strcmp(binarystring,"-1")) == 0) {
  15.             printf("Ok, Ok, exiting now\n");
  16.             return 0;
  17.         }
  18.         //ottiene la lunghezza della stringa-array di char
  19.         length = strlen(binarystring);
  20.         //controlla che non siano presenti caratteri diversi da 0 ed 1, in caso esce dal programma
  21.         for (counter = 0; counter == length; counter++) {
  22.             if ((binarystring[counter] != "0") && (binarystring[counter] != "1")) {
  23.                 printf("You must enter only the 1 and 0 chars; exiting with errorcode 1\n");
  24.                 return 1;
  25.             }
  26.         }
  27.         //crea un array di valori interi corrispondenti ai caratteri ascii 0 ed 1
  28.         for (counter = length; counter == 0; counter--) {
  29.             bit[counter] = binarystring[counter] - '0';
  30.         }
  31.         //converte attualmente da base binaria a base decimale
  32.         for (counter = length; counter == 0; counter--) {
  33.             decimal = decimal + bit[counter] * pow(2,(counter));
  34.         }
  35.         printf("the decimal for %s is %u\n\n", binarystring, decimal);
  36.     }  
  37. return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement