Convert between bases with decimals

F

ferran

Hi, does anybody know how to convert in C++ from base 10 to any other
base without loosing the decimal part of the actual value?

I came up with this algorithm to convert from decimal to any base but
I'm not sure what to do to include the decimal part.

//-----------------------------------------------------------
const char ccBaseChars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char sResult [80] = {0};
int iBase;
int iRemainder;

long double dValue = 14.3;

while (dValue > 0)
{
iRemainder = std::floorl(std::fmodl(dValue , iBase), 0);
Value = std::floorl(dValue / iBase);

if (iRemainder == iBase)
sResult = sResult + ccBaseChars [0];
else
sResult = sResult + ccBaseChars [iRemainder];
}
//-----------------------------------------------------------

<>Thanks for any help
 
V

Victor Bazarov

ferran said:
Hi, does anybody know how to convert in C++ from base 10 to any other
base without loosing the decimal part of the actual value?

Fractions can be converted. However, you have to take into consideration
the fact that while the integral part can be converted precisely in
a limited number of digits, the fractional part often cannot, and does
require infinite number of digits in the other base to represent a finite
number of digits in the original one. Example: "one and one third" if
written in _ternary_ system, would look like "1.1". However, in decimal
the same number is 1.333333333333333333333333333333333333333333333333...
Another pair: Decimal 1.1 in binary will be 1.0001100110011001100110011...
I came up with this algorithm to convert from decimal to any base but
I'm not sure what to do to include the decimal part.

Fractions are sort of simple: continuously multiply the number (the
fraction) by the base. If you get an integral part, write down that digit,
then subtract it. If you get exactly 0, stop. If you don't, keep going.
Sometimes, like when converting decimal 0.1 into binary, you _never_ get
precisly 0. That's when you get the _infinite_ number of digits in the
fractional part.
//-----------------------------------------------------------
const char ccBaseChars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char sResult [80] = {0};
int iBase;
int iRemainder;

long double dValue = 14.3;

while (dValue > 0)
{
iRemainder = std::floorl(std::fmodl(dValue , iBase), 0);
Value = std::floorl(dValue / iBase);

if (iRemainder == iBase)
sResult = sResult + ccBaseChars [0];
else
sResult = sResult + ccBaseChars [iRemainder];
}
//-----------------------------------------------------------

<>Thanks for any help
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top