summaryrefslogtreecommitdiff
path: root/src/tools/float.cpp
blob: 2c241f3d37f42c3c4ac069972980e1f9171c6caf (plain)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <bu/sio.h>
#include <bu/string.h>
#include <stdlib.h>
#include <math.h>

using namespace Bu;

Bu::String ftos( double dNum )
{
	if( dNum == 1.0 )
		return "0x1p+0";
	if( dNum == 0.0 )
		return signbit(dNum)?"-0x0p+0":"0x0p+0";
	if( dNum == -1.0 )
		return "-0x1p+0";
	Bu::String s("0x1.");
	if( signbit(dNum) )
	{
		s.prepend("-");
		dNum = -dNum;
	}
/*	
	for( int j = 0; j < 150 && dNum; j++ )
	{
		dNum = dNum*2;
		sio << dNum << " -- " << (int)dNum << sio.nl;
		if( (int)dNum == 0 )
			s += '0';
		else
		{
			s += '1';
			dNum -= 1.0;
		}
	}
	return s;
	*/
	int iPower = 0;
	if( dNum < 1.0 )
	{
		while( dNum < 1.0 )
		{
			dNum *= 2.0;
			iPower--;
		}
	}
	else if( dNum >= 2.0 )
	{
		while( dNum >= 2.0 )
		{
			dNum *= 0.5;
			iPower++;
		}
	}
	dNum -= (int)dNum;
	for( int j = 0; j < 150 && dNum; j++ )
	{
		dNum = dNum*16.0;
		s += "0123456789abcdef"[(int)dNum];
		dNum -= (int)dNum;
	}
	s.formatAppend("p%+d", iPower );
	return s;
}

double stof( const Bu::String &s )
{
	if( s == "0x1p+0" )
		return 1.0;
	if( s == "-0x1p+0" )
		return -1.0;
	if( s == "0x0p+0" )
		return 0.0;
	if( s == "-0x0p+0" )
		return 0.0;
	double dNum = 0.0;
	int iPPos = s.getSize()-1;
	for(; s[iPPos] != 'p'; iPPos--) { }
	for( int i = iPPos-1; s[i] != '.'; i-- )
	{
		if( s[i]>='0' && s[i]<='9' )
		{
			dNum += s[i]-'0';
		}
		else if( s[i]>='a' && s[i]<='f' )
		{
			dNum += s[i]-'a'+10.0;
		}
		dNum *= 0.0625;
	}

	dNum += 1.0;

	int iTop = strtol( s.getStr()+iPPos+1, NULL, 10 );
	if( iTop < 0 )
	{
		for( int j = 0; j > iTop; j-- )
		{
			dNum *= 0.5;
		}
	}
	else
	{
		for( int j = 0; j < iTop; j++ )
		{
			dNum *= 2.0;
		}
	}

	if( s[0] == '-' )
		return -dNum;
	return dNum;
}

int main( int argc, char *argv[] )
{
	for( int j = 1; j < argc; j++ )
	{
		double dNum = strtod( argv[j], NULL );

		String s = ftos( dNum );
		sio << "in:     " << dNum << sio.nl;
		sio << "mine:   " << s << sio.nl;
		printf("printf: %a\n", dNum );
		sio << "out:    " << stof( s ) << sio.nl;
		sio << "match:  " << (stof( s ) == dNum) << sio.nl << sio.nl;
	}

	return 0;
}