Float to Hex

Hello, I am trying to write a program that converts a floating point number into IEEE 32 and IEEE 64 bit hexadecimal representation. To do this, I can not use any built in converting functions of C++.

I was wondering if someone could show me a function that takes in an char array(max size 256) and prints the hexadecimal representation of that floating number. The number can be a negative or a positive.

For example:

Floating number = -0.25
IEEE 32 = BE800000
IEEE 64 = BFD0000000000000

I'm just looking for a way to get started. So any help will be appreciated. Thank you.
The question "number to hex" has been answered multiple times in this and other forums. I find it surprising that a Google search wouldn't give you the answer. For example: http://bit.ly/HUnDiM . Second result seem to point to the simplest way of doing this in C++.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <iomanip>

union ufloat 
{
    float f;
    unsigned long u;
};

union udoub
{
    double d;
    unsigned long long u;
};

int main()
{
    ufloat a;
    udoub b;
    a.f = -0.25f;
    b.d = -0.25;
    std::cout << std::setw(8) << std::setfill('0') << std::hex 
              << a.u << std::endl;
    std::cout << std::setw(16)<< std::setfill('0') << std::hex
              << b.u << std::endl;
    return 0;
}
be800000
bfd0000000000000
Press any key to continue . . .
Last edited on
Thank you guys for the response.

The reason I am having trouble with this program is because we are not allowed to use such functions as "hex", "atof()", "%x" or any built in class functions.

So, if anybody could set me in the right direction on how to go about doing this, that would greatly appreciated.
Well in that case, the code above at least gives you a unsigned int. That's 70% done. From there it isn't too hard to convert to hex values.
Topic archived. No new replies allowed.