Home > Software engineering >  Binary to Decimal conversion not working properly: C
Binary to Decimal conversion not working properly: C

Time:02-11

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;
    }
   };

CodePudding user response:

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

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

CodePudding user response:

Ok thanks everyone for helping! I will get the remainder of the number then the quotient to get the last digit instead of dealing with chars and the ascii table for now.

  • Related