I would like to read in a number, say a float, and allow the user to see what bit pattern is responsible for their input. How do I allow a variable to be printed or stored as an int or array as simple binary values instead of 0-9 or a-z, etc?
This doesn't do what I want it to. It instead gives an int with digits 0-9, which is obviously not a binary number.
int main(){
cout << "Please enter a float number." << endl;
float number;
cin >> number;
int bits = *((int*) &number);
cout << number << endl;
cout << bits << endl;
return 0;
}
The easiest (and C-friendly) way to do what you're trying to is to employ a pointer to char and use it to access the individual bytes of the float variable:
unsigned char *b = (unsigned char *)&number;
Then iterate over the bytes:
for (i = 0; i < sizeof number; i++)
{
printf("%02x", b[i]);
}
Note that this approach prints out a hexadecimal value, but that's directly convertible to a binary representation if you really want to do it that way:
for (i = 0; i < sizeof number; i++)
{
for (j = 0; j < CHAR_BIT; j++)
{
printf("%d", (b[i] >> j) & 1);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With