Wednesday, July 11, 2012

Write a program to convert binary string to decimal number

Parse the input string till end. On encountering a "1" compute power of 2 for the current position and add to a variable holding the result.

C++ program to convert binary string to decimal number

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;

int bin2dec(char* str) {
 int n = 0;
 int size = strlen(str) - 1;
        int count = 0;
 while ( *str != '\0' ) {
  if ( *str == '1' ) 
      n = n + pow(2, size - count );
  count++; 
  str++;
 }
 return n;
}

int main() {
 char* bin_str = "1100100";
 cout << bin2dec(bin_str) << endl;
}

Output:-
100

1 comment :

  1. This will work 100%
    int main(void){

    int i,sum = 0;
    char s[] = "1111";
    for (i = 0; s[i] != '\0'; i++){
    sum = (sum << 1) + s[i] - '0';
    }
    cout << "decimal number is " << sum << endl;

    }

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top