Use a union. I did this code to do exactly what you want:
// file floattobinary.cc
#include <string>
#include <inttypes.h> // for uint32_t
using namespace std;
void floatToBinary(float f, string& str)
{
union { float f; uint32_t i; } u;
u.f = f;
str.clear();
for (int i = 0; i < 32; i++)
{
if (u.i % 2) str.push_back('1');
else str.push_back('0');
u.i >>= 1;
}
// Reverse the string since now it's backwards
string temp(str.rbegin(), str.rend());
str = temp;
}
Below is a test program to run this function:
// file test.cc
#include <iostream>
#include <string>
#include <cstdlib> // for atof(3)
using namespace std;
void floatToBinary(float, string&);
int main(int argc, const char* argv[])
{
string str;
float f;
if (argc > 1)
{
f = static_cast<float>(atof(argv[1]));
floatToBinary(f, str);
}
cout << str << endl;
return 0;
}
Compile and run (I'm using GNU g++ on Linux):
me@mypc:~/college/c++/utils$ g++ -c floattobinary.cc
me@mypc:~/college/c++/utils$ g++ -c test.cc
me@mypc:~/college/c++/utils$ g++ -o test *.o
me@mypc:~/college/c++/utils$ ls
floattobinary.cc floattobinary.o test* test.cc test.o
me@mypc:~/college/c++/utils$ ./test 37.73
01000010000101101110101110000101
me@mypc:~/college/c++/utils$ ./test 2.0
01000000000000000000000000000000
me@mypc:~/college/c++/utils$ ./test 0.0
00000000000000000000000000000000
me@mypc:~/college/c++/utils$ ./test 237.74
01000011011011011011110101110001
me@mypc:~/college/c++/utils$ ./test 2.74e12
01010100000111110111110100101111
me@mypc:~/college/c++/utils$ ./test 2.74e13
01010101110001110101110001111010
me@mypc:~/college/c++/utils$ ./test -88.37
11000010101100001011110101110001