floating to hexadecimal - writing function

Hello geeks. My teacher gave me horrible homework i can't cope with. He told me to suggest a way to convert floating numbers given in decimal system(ex. 123.456) to hexadecimal system. I know there is a simple way to do it in iostream liblary (setting floatfield flag to hexfloat), but i just don't get this presentation. I tried to understand it, but it seems unnecessary for me. Mz task is to suggest a waz. So, my suggestion is: convert values before and after dot separately and print them in correct order (with dot between them). This is code i made:

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
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	const int P = 6;	// precission
	cout << fixed << setprecision(P);

	double d1=100.34;	// converted number
	cout << d1 << endl;

	int i1=int(d1);		// getting "before dot" part to int.
	
	double d2;			
	d2=d1-i1;		// substracting, to get only "after dot value"
	for (int i=0; i<P; ++i)
		d2*=10;		// multiplying P times to print it correctly
	int i2;
	i2=int(d2);		// getting "after dot" part to second int.

	cout << i1 << "." << i2;
				// printing together.

	cin.get();
}


I haven't use "hex" manipulator during printing to see if everything is correct. Unfortunatelly, it is not. Sometimes in "after dot" section get value one less than proper. I tried to figure out, where is the problem. I found out that CPU approximates double in odd way. How can i correct approximation in my program?

P.S. What should i do with number less that one? Then multiplying section does not work properly.

Jacob
Last edited on
http://en.wikipedia.org/wiki/Positional_notation#Base_conversion
Should help you.
You might probably want to use modf() function to separate floating and integral parts:
http://en.cppreference.com/w/cpp/numeric/math/modf
Last edited on
Topic archived. No new replies allowed.