Search code examples
c++floating-pointbitset

using bitset with floating types


Can you have bitset container of floating data types? Example:

bitset<sizeof(float)*sizeof(char)> second(5.5f);
cout << second.to_string() << endl;

It doesn't work correctly. what i'm trying to do is get the bit representation.


Solution

  • bitset only takes a unsigned long as its constructor argument. In your example the float is converted to unsigned long and then used as the argument.

    To get what you desire use something along the lines of:

    float f = 5.5f;
    std::bitset<sizeof(float)*CHAR_BIT> foo(*reinterpret_cast<unsigned long*>(&f));
    

    This reinterprets the "memory" the float is in as memory containing an unsigned long and thus "tricks" the constructor.