Floating point to binary conversion [duplicate]

2019-09-06 20:57发布

问题:

This question already has an answer here:

  • Floating Point to Binary Value(C++) 11 answers

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?

回答1:

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?..


标签: c++ bitset