Floating point to binary conversion [duplicate]

寵の児 提交于 2019-12-12 03:13:37

问题


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


来源:https://stackoverflow.com/questions/29307315/floating-point-to-binary-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!