Home > database >  Trying to convert binary to number, taking the input of binary as a string in C , but, I don’t know
Trying to convert binary to number, taking the input of binary as a string in C , but, I don’t know

Time:12-18

This is the code for the program:

#include <iostream>
#include <string>
using namespace std;

int binary_to_number(string BinaryInteger) {
    int sum{0};
    int powers_of_2{1};
    size_t size{BinaryInteger.size()};


    //reversing the string
    for (size_t i{0}; i< size; i  ) {
        BinaryInteger.at(i) = BinaryInteger.at(size - i);
    }
    //calculatiing the value of digit
    for (auto digit : BinaryInteger) {
        // as '1' in ascii code is 49, and '0' in ascii code is 48,
        // so, '1' - '0' will give the integer 1.
        digit = digit - '0';
        sum  = digit*powers_of_2;
        powers_of_2 *= 2;
    }
    return sum;
}

int main() {
    string n;
    cin >> n;
    cout <<  binary_to_number(n) << endl;
    return 0;
}

Unable to tell what’s the output because nothing (no errors, no output) is printed.

But, I think the problem is in the for loop which I used to reverse the string.

CodePudding user response:

An immediate issue I spot:

   for (size_t i{0}; i< size; i  ) {
       BinaryInteger.at(i) = BinaryInteger.at(size - i);
   }

When i is 0, BinaryInteger.at(size - i) is accessing out of bounds.

Even if this is tweaked to work, if we swap like this, we should only go halfway. Otherwise you're ultimately swapping characters back to their original order.


A little knowledge of the algorithms library1 makes this much simpler. Using rbegin and rend we can iterate over the string backwards without having to reverse the entire string first.

Starting with an initial value of 0 we can use std::accumulate to accumulate the final result. To aid in this, we'll capture power by reference in our lambda so we can increment it on each iteration, allowing us to build up the base appropriately. From there the math is pretty straightforward.

#include <string>
#include <cmath>
#include <numeric>
#include <iostream>

int binary_to_number(std::string bin) {
    int power = 0;
    return std::accumulate(
        bin.rbegin(), bin.rend(), 0, 
        [&power](int result, char ch){ 
            int base = std::pow(2, power  );
            int digit = ch - '0';
            return result   base * digit; 
        }
    );
}

int main() {
    std::string bin = "101";

    std::cout << binary_to_number(bin)
              << std::endl;
}

1 Some experience in functional programming doesn't hurt either.

CodePudding user response:

There are several ways to approach this problem. The most direct fix to the code in the question is to fix the loop:

for (std::size_t i = 0; i < size / 2;   i)
    std::swap(BinaryInteger[i], BinaryInteger[size - i - 1];

Note three changes: the loop runs only up to size / 2; running all the way would reverse the string twice, so the string would end up unchanged. The index of the second access is size - i - 1, not size - i; and the code uses std::swap, not simply assignment. (I also changed atto[]`; with a properly written loop there's no need to check that the index is valid).

But there's an easier way. Just use std::reverse:

std::reverse(BinaryInteger.begin(), BinaryInteger.end());

And even better, don't reverse the string. Just change the algorithm a bit:

for (auto digit : BinaryInteger)
    sum = sum * 2   digit - '0';
  • Related