Adsense 728 * 15

Search

Custom Search

C, C++ Program to Convert Binary Number to Decimal Number

Write a C, C++ program to convert binary number to decimal number. In this program, we take binary number as an input and our code will print their decimal representation.

For example -

Input      : 100 (Binary Number)
Output    : 4    (Decimal Number)

Input     : 111 (Binary Number)
Output  :  7    (Decimal Number)

C, C++ Program to Convert Binary Number to Decimal Number


How to Convert Binary to Decimal Number


Let's assume, we have to convert 100 to decimal number.

Decimal Number Conversion : 1 * 2 2   +  0 * 2 +  0 * 2 0 = 4

Similarly, we can convert any binary representation into decimal number.

Program to Convert Decimal to Binary Number.

C Program to Convert Binary to Decimal Number


#include <stdio.h>
#include <math.h>

int main() {
 
  int bnum, sum, rem, count=0;
 
  printf("Enter a binary number \n");
  scanf("%d",&bnum);
 
  /* Initialize a sum variable to 0 */
 
  sum = 0;
 
  while(bnum > 0){
  
      /* Take a Remainder */
  
      rem = bnum%10;
  
      /* If remainder is other than 0 and 1,
       then it is not a binary number. */

      if(rem==0 || rem==1 ){

        /* calculate sum. */
  
        sum = sum + rem *pow(2,count);
 
        /* Divide to reduce the number length. */
 
        bnum = bnum/10;
  
        /* Increment the count. */

        ++count;
   
      } else {

         printf(" Please enter valid binary number \n");
         return 0;    
      }  

  }
 
   printf("\n Decimal number is %d",sum);
  
   return 0;
}


Output:

Enter binary number 1000

Decimal number is 8

C++ Program to Convert Binary Number to Decimal Number


#include <iostream>
#include <math.h>
using namespace std;

int main() {
 
    int bnum, rem, count = 0, sum = 0, flag = 1;
    
    cout << "Enter a binary number \n";
    cin  >> bnum;
    
    while(bnum > 0) {
    
         rem = bnum % 10;
         
         // Binary number only contains 0 and 1
         if(rem == 0 || rem == 1) {
             
             sum = sum + rem * pow(2, count);
             
         } else {
             
             flag = 0;
             break;
         }
         
         //Increment count variable
         count++;
         bnum = bnum / 10;
    }
    
    if(flag) {
     cout << "Decimal number is " << sum;
    } else {
     cout << "Entered number is not a binary number";
    }
    
    return 0;
}



No comments:

Post a Comment