wfmath 1.0.3
A math library for the Worldforge system.
int_to_string.cpp
1#include "const.h"
2#include "int_to_string.h"
3
4#include <climits>
5
6namespace WFMath {
7
8// This takes a pointer pointing to the character after the end of
9// a buffer, prints the number into the tail of the buffer,
10// and returns a pointer to the first character in the number.
11// Make sure your buffer's big enough, this doesn't check.
12static char* DoIntToString(unsigned long val, char* bufhead)
13{
14 // deal with any possible encoding problems
15 const char digits[10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
16
17 *(--bufhead) = '\0';
18
19 if(val == 0)
20 *(--bufhead) = '0';
21 else do {
22 *(--bufhead) = digits[val % 10];
23 val /= 10;
24 } while(val);
25
26 return bufhead;
27}
28
29#ifndef _MSC_VER
30// note that all floating point math is done at compile time
31static const double log_10_of_2 = 0.30102995664;
32static const unsigned ul_max_digits = (unsigned)
33 (8 * sizeof(unsigned long) // number of bits
34 * log_10_of_2 // base 10 vs. base 2 digits
35 + 1 // log(1) == 0, have to add one for leading digit
36 + numeric_constants<CoordType>::epsilon()); // err on the safe side of roundoff
37#else // _MSC_VER
38static const unsigned ul_max_digits = 10;
39#endif // _MSC_VER
40
41std::string IntToString(unsigned long val)
42{
43 static const unsigned bufsize = ul_max_digits + 1; // add one for \0
44 char buffer[bufsize];
45
46 return DoIntToString(val, buffer + bufsize);
47}
48
49// Deals with the fact that while, e.g. 0x80000000 (in 32 bit),
50// is a valid (negative) signed value, the negative
51// of it can only be expressed as an unsigned quantity.
52static unsigned long SafeAbs(long val)
53{
54#if LONG_MAX + LONG_MIN >= 0
55 // a signed variable can hold -LONG_MIN, we're completely safe
56 return (val >= 0) ? val : -val;
57#else
58 if(val >= 0)
59 return val;
60 else if(val >= -LONG_MAX) // -LONG_MAX is a valid signed long
61 return -val;
62 else // LONG_MAX + val < 0
63 return LONG_MAX + (unsigned long) (-(LONG_MAX + val));
64#endif
65}
66
67std::string IntToString(long val)
68{
69 static const unsigned bufsize = ul_max_digits + 2; // one for \0, one for minus sign
70 char buffer[bufsize];
71
72 char* bufhead = DoIntToString(SafeAbs(val), buffer + bufsize);
73
74 if(val < 0)
75 *(--bufhead) = '-';
76
77 return bufhead;
78}
79
80} // namespace WFMath
Generic library namespace.
Definition: shape.h:41
static FloatType epsilon()
This is the attempted precision of the library.