### how do I get a space in my output using union to convert a float into binary?

This is what I have:

void print_Float()
{
float number;

cout << " \n Enter a float: ";
cin >> number;
cout << " \n";

union
{
float input; // assumes sizeof(float) == sizeof(int)
int output;
}
data;
data.input = number;

std::bitset<sizeof(float) * CHAR_BIT> binary(data.output);
std::cout << " The binary representation for " << number << " is: " << binary << std::endl;

cout << endl;

return;
}

This is my output:
Enter a float: 5.6
The binary representation for 5.6 is: 01000000101100110011001100110011

What I need is a space added to output:
Enter a float: 5.6
The binary representation for 5.6 is: 0100 0000 1011 0011 0011 0011 0011 0011

how can I do it using the union?

I managed to get it to work by:

void printFloat()
{
float number;

cout << " \n Enter a float: ";
cin >> number;
cout << " \n";
cout << " The binary representation for " << number << " is: ";
int i;
int c = *(int*)&number;
for(i=0;i<32;i++)
{
if(i%4==0)
printf(" ");
if(b==0)
cout<<"0";
else
cout<<"1";
}
cout << endl;
cout << endl;
}
Last edited on
You could convert the binary information into a string, and utilize string functions to adapt it how you'd like.
Whatever it is you are trying to do, it is the wrong thing to do in at least two ways.

Hmm... unless you just want to see the bits of the number.

A bitset doesn't directly support what you are trying to do, but you can certainly do it a number of ways. The basic premise of all of them is to first convert to a string, modify the string (insert spaces), and then print the string.

Without any fanciness:
 1234567891011121314 std::string add_spaces( const std::bitset & bits, std::size_t n ) { std::string result; std::string bitstring = bits.to_string(); std::size_t ni = bitstring.size(); std::size_t si = bitstring.size(); while (si--) { result += bitstring[ si ]; if ((--ni % n) == 0) result += ' '; } return result; }

Now you can use it like:

cout << add_spaces( binary, 4 ) << "\n";

Hope this helps.
I managed to get it to work by:

void printFloat()
{
float number;

cout << " \n Enter a float: ";
cin >> number;
cout << " \n";
cout << " The binary representation for " << number << " is: ";
int i;
int c = *(int*)&number;
for(i=0;i<32;i++)
{
if(i%4==0)
printf(" ");
if(b==0)
cout<<"0";
else
cout<<"1";