Hello everyone. I've been working on a binary to decimal converter, and it works for most numbers, but seems to fail at smaller numbers. For example, 10000 does not return 16.
#include <iostream> //std::cout, std::cin, std::endl
#include <string> //std::string
//this approach is assuming that the binary number is unsigned and not signed.
int main()
{
std::string binary = "";
std::cout << "Please enter a binary number: ";
std::cin >> binary;
//auto is a c++11 feature
auto rit = binary.rbegin(); //reverse iterator so we can iterate backwards
unsigned bit = 1; //the value of the current bit
unsigned decimal = 0; //we are hoping it is within range
while(rit != binary.rend()) //iterate the entire string
{
if(*(rit++) == '1') //check if the current bit is set, then move to next bit
{
decimal += bit;
}
bit <<= 1; //shift it to the left one bit
}
std::cout << "Binary value: " << binary << '\n'
<< "Decimal value: " << decimal << std::endl;
return 0;
}
There are obviously a large amount of very different ways to do this, I would however say that you are doing one of the more confusing ways.
By the way your code gave me 16 when I entered 10000 are you sure you built the newest version or input it correctly? Though they problems may be related to using doubles instead of pure ints. Doubles are not 100% accurate.
it definitely does output 20 for 10000 when I compile my program in Code::Blocks.
it is probably because of the doubles. They are not completely accurate. Try using integers only so it is more accurate. Though your program seems to "work" when you run it on cpp.sh.