ordinary
ordinary

Reputation: 6133

Is this an inefficent way to convert from a binary string to decimal value?

  while(i < length)
  {
    pow = 1;
    for(int j = 0; j < 8; j++, pow *=2)
    {   
      ch += (str[j] - 48) * pow;
    }   
    str = str.substr(8);
    i+=8;
    cout << ch; 
    ch = 0;
  }

This seems to be slowing my program down a lot. Is it because of the string functions I'm using in there, or is this approach wrong in general. I know there's the way where you implement long division, but I wanted to see if that was actually more efficient than this method. I can't think of another way that doesn't use the same general algorithm, so maybe it's just my implementation that is the problem.

Upvotes: 1

Views: 242

Answers (5)

Kerrek SB
Kerrek SB

Reputation: 477140

Minimize the number of operations and don't compute things more than once. Just multiply and move up:

unsigned int result = 0;

for (char * p = str; *p != 0; ++p)
{
    result *= 2;
    result += (*p - '0');  // this is either 0 or 1
}

The scheme is readily generalized to any base < 10.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881633

Perhaps you want might to look into using the standard library functions. They're probably at least as optimised as anything you run through the compiler:

#include <iostream>
#include <iomanip>
#include <cstdlib>

int main (void) {
    const char *str = "10100101";

    // Use str.c_str() if it's a real C++ string.
    long int li = std::strtol (str, 0, 2);

    std::cout
        << "binary string = " << str
        << ", decimal = " << li
        << ", hex = " << std::setbase (16) << li
        << '\n';
    return 0;
}

The output is:

binary string = 10100101, decimal = 165, hex = a5

Upvotes: 5

Bo Persson
Bo Persson

Reputation: 92271

You are doing some things unnecessarily, like creating a new substring for each each loop. You could just use str[i + j] instead.

It is also not necessary to multiply 0 or 1 with the power. Just use an if-statement.

  while(i < length)
  {
     pow = 1;
     for(int j = 0; j < 8; j++, pow *=2)
     { 
         if (str[i + j] == '1')
            ch += pow;
     }
     i+=8; 
     cout << ch; 
     ch = 0; 
  } 

This will at least run a bit faster.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409196

How about something like:

int binstring_to_int(const std::string &str)
{
    // 16 bits are 16 characters, but -1 since bits are numbered 0 to 15
    std::string::size_type bitnum = str.length() - 1;
    int value = 0;

    for (auto ch : str)
    {
        value |= (ch == '1') << bitnum--;
    }

    return value;
}

It's the simplest I can think of. Note that this uses the new C++11 for-each loop construct, if your compiler can't handle it you can use

for (std::string::const_iterator i = str.begin(); i != str.end(); i++)
{
    char ch = *i;
    // ...
}

Upvotes: 0

Vijay
Vijay

Reputation: 67231

short answer could be:

long int x = strtol(your_binary_c++_string.c_str(),(char **)NULL,2)

Probably you can use int or long int like below:

Just traverse the binary number step by step, starting from 0 to n-1, where n is the most significant bit(MSB) , multiply them with 2 with raising powers and add the sum together. E.g to convert 1000(which is binary equivalent of 8), just do the following

1 0 0 0 ==> going from right to left

0 x 2^0 = 0 0 x 2^1 = 0; 0 x 2^2 = 0; 1 x 2^3 = 8; now add them together i.e 0+0+0+8 = 8; this the decimal equivalent of 1000. Please read the program below to have a better understanding how the concept work. Note : The program works only for 16-bit binary numbers(non-floating) or less. Leave a comment if anything is not clear. You are bound to receive a reply.

// Program to convert binary to its decimal equivalent

#include <iostream>
#include <math.h>

int main()
{
     int x;
     int i=0,sum = 0;
     // prompts the user to input a 16-bit binary number
     std::cout<<" Enter the binary number (16-bit) : ";
     std::cin>>x;

     while ( i != 16 ) // runs 16 times
     {
          sum += (x%10) * pow(2,i);
          x = x/10;
          i++;
     }
     std::cout<<"\n The decimal equivalent is : "<<sum;
     return 0;
}

Upvotes: 0

Related Questions