I just wrote the following C++ code in order to convert a fractional number into its corresponding binary format.
double get_decimal_part(double num) {
long x = static_cast<long>(num);
return (num - static_cast<double>(x));
}
long get_real_part(double num) {
return static_cast<long>(num);
}
string fraction_to_binary(double num) {
string decimal_binary = "";
double decimal_part = get_decimal_part(num);
while ( decimal_part > 0 ) {
double temp = decimal_part * 2;
if ( get_real_part(temp) == 0 ) decimal_binary += "0";
else decimal_binary += "1";
decimal_part = get_decimal_part(temp);
}
return decimal_binary;
}
int main() {
cout << "3.50 - " << fraction_to_binary(3.50) << endl;
cout << "3.14 - " << fraction_to_binary(3.14) << endl;
}
The output would be :-
3.50 - 1
3.14 - 001000111101011100001010001111010111000010100011111
I’d have the following questions regarding the same :-
- In the case if “3.50”, my implementation would give “1” as the output — how can I go about modifying my implementation in order to account for the trailing “0” in 3.50?
- If there were any library functions that could help me get the precision of a floating point number? I’m guessing I could use that information to modify my implementation.
[EDIT]
I also tried using the following to convert a float to a string but it wouldnt help either.
stringstream ss;
ss << my_float;
cout << string(ss.str()) << endl;
Before answering your specific questions, what’s wrong with
modffor this?With regards to your specific questions:
What trailing
"0"? You’re talking about a textrepresentation here. Inside the machine,
"3.5"and"3.50"correspond to the same number, and have the same representation.
There is a library function which returns the precision of a
floating point number:
std::numeric_limits<double>::digits(except that it isn’t a function, but a constant). But if you
want to break a number down into its integral and whole number
parts,
modffits the bill exactly. And unlike your code, willactually work, for all values of
double.EDIT:
Looking closer at the larger picture of what you are trying to
do: my approach would be to use
frexpto extract the base 2exponent, then
ldexpto scale the number into the range[0.5...1)Then loopstd::numeric_limits<double>::digitstimes, each time multiplying by
2, and checking that: if theresults of the multiplication are less than 1, then insert a 0
digit; otherwise, insert a 1 digit and subtract 1. (Note
that all of the above actions will be exact if the machine
floating point is base 2, or a power of 2.)