Im having trouble getting this function to work. I need to take an 8-bit binary number in as a string and convert it to decimal. I already have a function to validate the binary number, making sure it's all 1's or 0's, and only 8 bits long. I can't get the conversion to work though. If I enter "11111111" as my string it should return 255 but it returns 128. When I go through debugging, it shows that my if statement resolves to false at biNum.substr positions 0-6, only resolving to true at the last position. Any help would be amazing. I've been working on this for 3 days and can't get anywhere.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int ConvertFromBinary(string biNum, int len)
{
int num = 0;
for (int i = 0; i < len; i++)
{
if (biNum.substr(i) == "1")
{
num = num + pow(2, i);
}
}
return num;
}
Change if (biNum.substr(i) == "1")
to if (biNum[i] == '1')
(Note the single quotes as well as the simple index.) substr doesn't do what you appear to think it does.
Other things:
- you don't need to pass len as a parameter; biNum is a std::string so just use biNum.size()
- pow( 2, i ) actually returns a double; you will probably get away with it, but this sort of thing is a recipe for floating-point truncation errors
- in future, please give us complete code so that we can test it without having to write in all the headers and a driver routine.
int ConvertFromBinary(string biNum)
{
int num = 0;
int len = biNum.size();
int real_pos = len - 1;
for (int i = 0; i < len; i++)
{
if (biNum[i] == '1')
{
num = num + pow(2, real_pos);
}
--real_pos;
}
return num;
}
some little stuff...
pow is kinda slow for integer powers. many of us keep a custom "ipow" for integers for speed, and to avoid any of the mentioned roundoff issues. Here, a lookup table might do.
num+= …
is the same as
num = num+...
and you should use this shorthand. logic and arithmetic operators have a version eg -+ *= ^= and so on
its possible to write it without the if, such that it just adds zero when zero comes in and adds 2^n when a 1 comes in. This is good for practice, to see if you can do it, as sometimes this is a useful trick. Here, its just the numeric value ('1'-'0' or '0'-'0') * the pow expression, or in Boolean, (str[x]=='1')*pow...
#include <iostream>
#include <string>
usingnamespace std;
int ConvertFromBinary( string biNum )
{
int num = 0;
int len = biNum.size();
for ( int i = 0; i < len; i++ )
{
if ( biNum[i] == '1' ) num += 1 << len - 1 - i;
}
return num;
}
int main()
{
string tests[] = { "11111111", "1100", "0011", "101010", "10111" };
for ( string s : tests ) cout << s << " " << ConvertFromBinary( s ) << '\n';
}