I need to write a C++ program to print the binary pattern of a float. Can anyone post examples of the reinterpret_cast function? I had trouble finding some.
The only standards-conforming way to access the binary pattern of a float is to reinterpret_cast it as a char*. Once you have a char*, you can do whatever, for example, convert to bitset for easy printing:
1 2 3 4 5 6 7 8 9 10
#include <bitset>
#include <iostream>
int main()
{
float f = 0.125;
char* bits = reinterpret_cast<char*>(&f);
for(std::size_t n = 0; n < sizeof f; ++n)
std::cout << std::bitset<8>(bits[n]);
std::cout << '\n';
}
int i; // declare variables
float f;
int bit = 0;
cout << "Enter a floating point number: "; // enter a float
cin >> f; // read in the number
int *b = reinterpret_cast<int*>(&f); // use reinterpret_cast function
for (int k = 31; k >=0; k--) // for loop to print out binary pattern
{
bit = ((*b >> k)&1); // get the copied bit value shift right k times, then and with a 1.
cout << bit; // print the bit.
}