I have a question on converting a 17-bit unsigned binary number to double-type. Let say the binary number is 1_0011_0110_1110_1001; // which is 0.60725 in decimal
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
//======================================================================
double baseDec( string s, int base )
{
// Keep digits and point
string digits;
string fraction;
for ( char c : s ) if ( c == '.' || isdigit( c ) ) digits += c; // currently allows up to base 10
// Split into whole and fractional part
int pos = digits.find( '.' );
if ( pos != string::npos )
{
fraction = digits.substr( pos + 1 );
digits = digits.substr( 0, pos );
}
double result = 0;
// Compound whole-number part
for ( int i = 0; i < digits.size(); i++ ) result = base * result + ( digits[i] - '0' );
// Compound fractional part
double value = 1.0 / base;
for ( int i = 0; i < fraction.size(); i++ )
{
if ( fraction[i] != 0 ) result += value * ( fraction[i] - '0' );
value /= base;
}
return result;
}
//======================================================================
int main()
{
string s;
int base;
cout << "Input base (2-10): ";
cin >> base;
cout << "Input unsigned number in that base (with/without point): ";
cin >> s;
cout << "Decimal is " << fixed << setprecision( 5 ) << baseDec( s, base ) << endl;
}
Input base (2-10): 2
Input unsigned number in that base (with/without point): 0.10011011011101001
Decimal is 0.60725
Input base (2-10): 7
Input unsigned number in that base (with/without point): 24.11
Decimal is 18.16327