I'm wondering if there is a way to represent a float using a char in C++?
For example:
int main()
{
float test = 4.7567;
char result = charRepresentation(test);
return 0;
}
I read that probably using bitset I can do it but I'm not pretty sure.
Let's suppose that my float variable is 01001010 01001010 01001010 01001010 in binary.
If I want a char array of 4 elements, the first element will be 01001010, the second: 01001010 and so on.
Can I represent the float variable in a char array of 4 elements?
I suspect what you're trying to say is:
int main()
{
float test = 4.7567;
char result[sizeof(float)];
memcpy(result, &test, sizeof(test));
/* now result is storing the float,
but you can treat it as an array of
arbitrary chars
for example:
*/
for (int n = 0; n < sizeof(float); ++n)
printf("%x", result[n]);
return 0;
}
Edited to add: all the people pointing out that you can't fit a float
into 8 bits are of course correct, but actually the OP is groping towards the understanding that a float
, like all atomic datatypes, is ultimately a simple contiguous block of bytes. This is not obvious to all novices.
the best you can is create custom float that is byte size. or use char as fixed point decimal. on all cases this will lead to significant loss of precision.
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