Re: Convert between bases with decimals

From: Victor Bazarov (v.Abazarov_at_comAcast.net)
Date: 11/28/03


Date: Fri, 28 Nov 2003 16:51:44 GMT


"ferran" <ferran9@yahoo.com> wrote...
> 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


Loading