Possible Duplicate:
Float to binary in C++
I want to print out the binary representation of a float number in C++. Not very practical, just out of curiosity.
The following program doesn't compile though. The reinterpret_cast fails. What kind of cast can I use so that I can do the " &(1 << i) " part?
#include <iostream>
using namespace std;
void toBinary(float num) {
int numi = reinterpret_cast<int>(num);
cout << num << " " << numi << endl;
for (int i = 0; i < 8 * sizeof(num); i++){
if (numi & (1<<i)) {
cout << 1;
} else {
cout << 0;
}
}
cout << endl << endl;
}
int main() {
float a;
cout << sizeof(int) << " " << sizeof(float) << endl;
a = 13.5;
toBinary(a);
toBinary(13.9);
toBinary(2 * a);
toBinary(-a);
}
There's a much easier way. Take a pointer to the float, and reinterpret_cast it to a pointer to char. Now loop through sizeof(float) and convert each char to 8 binary digits. This method works for doubles too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With