printing float as a hex number

hello all

If a user enters a floatint point number like 10.1, I want to print out the hex number in floating point. The %X specifer allows for an int to be printed as a hex number and I heard you could do the samething with floating point numbers with casting and pointers but I can't seem to figure it out. Anyone have any ideas? Thanks
I'm sure somewhere there is some archaic definition of a hexadecimal floating point specification.

However if you want a translation of a literal such as 10.1 (decimal) to A.1999999999 (hexadecimal) - that is stright forward enough, I remember the formula from myschool days.

But to be able to cast a floating point to a hexadecimal - I've never heard of such a thing in C/C++ - there is no such intrinsic C/C++ type as hexadecimal floating point. (in JAVA mayhaps).
Last edited on
You could try analyzing the data in memory to see how they store it (i.e. integer part somewhere, decimal part somewhere else) and then try to do stuff with that...but I think that it would be easiest to just do the literal translation.
Yeah, no sense in making it hard. Just split it into whole number + fractional + exponent parts and convert the individual parts to hex. Hence:

10.11e12 == 0xA.BeC

Looks funny, but that's exactly it.

[If you are confused about the fractional part, consider multiplying the decimal number by 10eN places (where N is your significant digits), then converting, then dividing by 16eM places (where 16N == 10M). N,M can be on bit-resolution.]

Hope this helps.
How weird .

Noticed this morning that cout has a manipulator called hexfloat which works like we described above.
Last edited on
Slick! I didn't know that was there...
Topic archived. No new replies allowed.