Reputation:
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 :-
[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;
Upvotes: 0
Views: 2932
Reputation: 154007
Before answering your specific questions, what's wrong with
modf
for this?
With regards to your specific questions:
What trailing "0"
? You're talking about a text
representation 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, modf
fits the bill exactly. And unlike your code, will
actually work, for all values of double
.
Looking closer at the larger picture of what you are trying to
do: my approach would be to use frexp
to extract the base 2
exponent, then ldexp
to scale the number into the range
[0.5...1)
Then loop std::numeric_limits<double>::digits
times, each time multiplying by 2
, and checking that: if the
results 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.)
Upvotes: 3