Anybody willing to give simple hexadecimal help?
This has been giving me trouble over this past week, I'm desperate, can you guys help?
"write C++ code to display the hexadecimal value stored in memory for the floats q and t below,
float q = 0.1,
t = 0.5;"
I've tried all sorts of things, but the output I always get for "q" is 0.1 . Why is this? I've used the simple
std::hex << q <<
And I've even gotten fancy with that whole
setf(std::ios::hex) thing.
My MOST RECENT attempt looks like this:
#include <iostream>
#include <iomanip>
int main()
{
float number;
number = 0.5;
std::cout.setf(std::ios::hex);
std::cout << "what about the hex function?: " << number << "\n";
return (0);
}
This does nothing. Obviously, this is either WAY off, or I'm doing it wrong.
If you guys have ANY ideas, suggestions, comments, please share them! Even the smallest and seemingly insignificant responses will be greatly appreaciated.
You'll probably have to write your own algorithm.
I'm about 95% sure that hk_mp5kpdw is right. The built-in hex conversion won't work with floats. In that case, you'll have to write your own algorithm.
Instead of a tenths-place, you have a sixteenths place, and you have a 256th place, etc :
So, 0.5 decimal is 0.8 hex (8 16ths = 8/16)
With a little trial & error and playing around with a calculator, I get 0.1 Decimal = 0.199 hex (approx).
That's 1*(1/16) + 9*(1/256) + 9*(1/4096)
It's probably a repeating "hexadecimal". That might be one point of the exercise... to show that some "nice" decimal numbers can't be accurately stored in binary (or hex).
Note that 0.199 hex does NOT approximate 0.200 hex... 0.1FF is close to 0.200 hex. Also, if it turns-out to be a repeating number: 0.19999 hex rounds to 0.199A.