Mike_King

DecToBin / BinToDec converter

Jan 30th, 2012
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int DecToBin(void){
  4.     int n, o, i = 0;
  5.     int *data;
  6.    
  7.     printf("Enter number: ");
  8.     scanf("%d" , &n);
  9.    
  10.     printf("Dec to bin: ");
  11.     while(n){
  12.         o = n%2;
  13.         if(o == 1){
  14.              data[i] = 1;
  15.         }
  16.         else{
  17.              data[i] = 0;
  18.         }
  19.         i++;
  20.         n /= 2;
  21.     }
  22.     for(i - 1; i >= 0; i--){
  23.         if(data[i] == 1){
  24.             printf("1");
  25.           }
  26.         else if(data[i] == 0){
  27.             printf("0");
  28.         }
  29.     }
  30.     printf("\n\n");
  31. }
  32.  
  33. int BinToDec(void){
  34.     int i, sum = 0, d = 1;
  35.     char *data;
  36.     printf("Enter number: ");
  37.     scanf("%s", data);
  38.  
  39.     for(i = strlen(data)-1; i >= 0; i--){
  40.         if(data[i] == '1'){
  41.             sum += d;
  42.         }
  43.         d = d * 2;
  44.     }
  45.  
  46.     printf("Bin to dec: %d\n\n", sum);
  47. }
  48.  
  49. int main(void)
  50. {
  51.     int s = 0;
  52.  
  53.     while(1){
  54.         printf("Enter 1 to convent 10 in 2\nEnter 2 to convent 2 in 10\nEnter 3 to exit\n>");
  55.         scanf("%d", &s);
  56.         printf("\n");
  57.        
  58.         if(s == 1){
  59.             DecToBin();
  60.         }
  61.         else if(s == 2){
  62.             BinToDec();
  63.         }
  64.         else if(s == 3){
  65.             break;
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment