Search code examples
c++bitset

Floating point to binary conversion


I am working on a project of converting any real number into binary using IEEE 754 format.
My first trial is using the bitset library type for conversion of the number then i can worry about dividing the whole number into sign bit, exponent and mantissa.

int foo;
cin >> foo;

bitset<32> my_bit(foo);

As it turns out, bitset will do with signed integers only.
How do i include floating point numbers?
Can i accomplish my task with another library type that is as fairly simple as bitset?


Solution

  • Actually, bitset constructor accepts unsigned long in C++ 03 and unsigned long long in C++ 11. Now, as for storing float in a bitset, this should do the trick:

    float f = 0.0f;
    cin >> f;
    bitset<32> my_bit(*(uint32_t*)&f); // my_bit? What kind of a name is that, anyway?..