Ad

Binary To Decimal Conversion Not Working Properly: C++

- 1 answer

can anyone please help me with this code I wrote. I am multiplying the digit from the string that is either 0 or 1 by 2 to the power of "power" which is an integer incrementing every time we loop and I am adding the result to the return value...but for some reason it's not working.

So for example: "10" is returning 48 instead of 2

#include <iostream>
#include <string>
#include <cmath>
#include <sstream>

using BINARY = unsigned long;
typedef int BI;

class Binary_
{
private:
std::string binary_string;
BINARY return_binary()
{
    BINARY result = 0;
    BI power = 0, binary_value = 0;
    for(int i = this->binary_string.length() - 1; i > 0; i--)
    {
        std::string binary_char_hold = std::to_string(this->binary_string[i]);
        std::stringstream Binary_stream(binary_char_hold);
        Binary_stream >> binary_value;
        result = result + (binary_value * pow(2, power));
        power++;
    }
    return result;
 }
 public :
    BINARY get_binary(std::string binary_string)
    {
        BINARY binary_val = 0;
        for (int i = 0; i < binary_string.length(); i++)
        {
            if (binary_string[i] == '0' || binary_string[i] == '1') { this->binary_string = 
            binary_string; binary_val = return_binary(); }
            else this->binary_string = "Binary value you entered is invalid and not of base 2 system!";
        }
        return binary_val;
    }
   };
Ad

Answer

There is another simpler implementation by strtoull() function for your problem.

More details can be found at C++: binary std::string to decimal

Ad
source: stackoverflow.com
Ad