Floating point to binary conversion [duplicate]

2019-09-06 20:54发布

This question already has an answer here:

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?

标签: c++ bitset
1条回答
ら.Afraid
2楼-- · 2019-09-06 21:23

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?..
查看更多
登录 后发表回答