-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.c
117 lines (114 loc) · 2.12 KB
/
util.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
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
#include "util.h"
void reverse(char str[], int length)
{
int start = 0;
int end = length - 1;
while(start < end)
{
char t;
t = *(str + start);
*(str + start) = *(str + end);
*(str + end) = t;
start++;
end--;
}
}
unsigned char IntToStr(uint32_t Value, char *buf)
{
unsigned char i = 0;
if(!Value)
{
buf[0] = '0';
buf[1] = 0;
return 1;
}
while(Value)
{
buf[i] = '0' + Value % 10;
i++;
Value /= 10;
}
reverse(buf, i);
buf[i] = 0;
return i;
}
//union
//{
// float f;
// struct
// {
// unsigned int mantissa_lo : 16;
// unsigned int mantissa_hi : 7;
// unsigned int exponent : 8;
// unsigned int sign : 1;
// };
//} helper;
unsigned char FloatToStr(float f, char *Buf)
{
long mantissa, int_part, frac_part;
short exp2;
typedef union
{
long L;
float F;
} TLF;
TLF x;
char *p;
if(f == 0.0f)
{
Buf[0] = '0';
Buf[1] = '.';
Buf[2] = '0';
Buf[3] = 0;
return 0;
}
x.F = f;
exp2 = (unsigned char)(x.L >> 23) - 127;
mantissa = (x.L & 0xFFFFFF) | 0x800000;
frac_part = 0;
int_part = 0;
if(exp2 >= 31)
return _FTOA_TOO_LARGE;
else if(exp2 < -23)
return _FTOA_TOO_SMALL;
else if(exp2 >= 23)
int_part = mantissa << (exp2 - 23);
else if(exp2 >= 0)
{
int_part = mantissa >> (23 - exp2);
frac_part = (mantissa << (exp2 + 1)) & 0xFFFFFF;
}
else /* if (exp2 < 0) */
frac_part = (mantissa & 0xFFFFFF) >> -(exp2 + 1);
p = Buf;
if(x.L < 0)
*p++ = '-';
if(int_part == 0)
*p++ = '0';
else
{
// ltoa(p, int_part, 10);
IntToStr((uint32_t)int_part, p);
while(*p)
p++;
}
*p++ = '.';
if(frac_part == 0)
*p++ = '0';
else
{
unsigned char m, max;
max = sizeof(Buf) - (unsigned char)(p - Buf) - 1;
if(max > 7) max = 7;
for(m = 0; m < max; m++) // print BCD
{
frac_part = (frac_part << 3) + (frac_part << 1); // frac_part *= 10;
*p++ = (frac_part >> 24) + '0';
frac_part &= 0xFFFFFF;
}
for(p--; p[0] == '0' && p[-1] != '.'; --p); // delete ending zeroes
p++;
}
*p = 0;
return 0;
}