Floating Point to Binary Value(C++)
Use union and bitset:
#include <iostream>
#include <bitset>
#include <climits>
int main()
{
union
{
float input; // assumes sizeof(float) == sizeof(int)
int output;
} data;
data.input = 2.25125;
std::bitset<sizeof(float) * CHAR_BIT> bits(data.output);
std::cout << bits << std::endl;
// or
std::cout << "BIT 4: " << bits[4] << std::endl;
std::cout << "BIT 7: " << bits[7] << std::endl;
}
It may not be an array but you can access bits with [] operator as if you were using an array.
Output
$ ./bits
01000000000100000001010001111011
BIT 4: 1
BIT 7: 0
int fl = *(int*)&floatVar; //assuming sizeof(int) = sizeof(float)
int binaryRepresentation[sizeof(float) * 8];
for (int i = 0; i < sizeof(float) * 8; ++i)
binaryRepresentation[i] = ((1 << i) & fl) != 0 ? 1 : 0;
Explanation
(1 << i)
shifts the value 1
, i
bits to the left.
The &
operator computes the bitwise and of the operands.
The for
loop runs once for each of the 32 bits in the float. Each time, i
will be the number of the bit we want to extract the value from. We compute the bitwise and of the number and 1 << i
:
Assume the number is: 1001011, and i = 2
1<<i
will be equal to 0000100
10001011
& 00000100
==========
00000000
if i = 3
then:
10001011
& 00001000
==========
00001000
Basically, the result will be a number with i
th bit set to the i
th bit of the original number and all other bits are zero. The result will be either zero, which means the i
th bit in the original number was zero or nonzero, which means the actual number had the i
th bit equal to 1
.
other approach, using stl
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
float f=4.5f;
cout<<bitset<sizeof f*8>(*(long unsigned int*)(&f))<<endl;
return 0;
}