PropWare  3.0.0.229
C++ objects and CMake build system for Parallax Propeller
nonstdlib.cpp
Go to the documentation of this file.
1 
10 #include <stdlib.h>
11 #include <ctype.h>
12 #include "nonstdlib.h"
13 
14 // Amazingly itoa and utoa are not part of the C standard and thus not part
15 // of GCC. They were added in the AVR port, so they are included here.
16 
21 void strreverse(char* begin, char* end)
22 {
23  char aux;
24 
25  while(end>begin)
26  aux=*end, *end--=*begin, *begin++=aux;
27 }
28 
29 static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz";
30 
31 void itoa(int value, char* str, int base)
32 {
33  char* wstr = str;
34  int sign;
35  div_t res;
36 
37  // Validate base
38  if (base<2 || base>35)
39  {
40  *wstr='\0';
41  return;
42  }
43 
44  // Take care of sign
45  if ((sign=value) < 0)
46  value = -value;
47 
48  // Conversion. Number is reversed.
49  do
50  {
51  res = div(value,base);
52  *wstr++ = num[res.rem];
53  } while (value=res.quot);
54 
55  if (sign<0)
56  *wstr++='-';
57 
58  *wstr='\0';
59 
60  // Reverse string
61  strreverse(str, wstr-1);
62 }
63 
64 void utoa(unsigned int value, char* str, int base)
65 {
66  char* wstr = str;
67  div_t res;
68 
69  // Validate base
70  if (base<2 || base>35)
71  {
72  *wstr='\0';
73  return;
74  }
75 
76  // Conversion. Number is reversed.
77  do
78  {
79  res = div(value,base);
80  *wstr++ = num[res.rem];
81  } while (value=res.quot);
82 
83  *wstr='\0';
84 
85  // Reverse string
86  strreverse(str, wstr-1);
87 }
88 
89 void ltoa(long value, char* str, int base)
90 {
91  char* wstr = str;
92  long sign;
93  div_t res;
94 
95  // Validate base
96  if (base<2 || base>35)
97  {
98  *wstr='\0';
99  return;
100  }
101 
102  // Take care of sign
103  if ((sign=value) < 0)
104  value = -value;
105 
106  // Conversion. Number is reversed.
107  do
108  {
109  res = div(value,base);
110  *wstr++ = num[res.rem];
111  } while (value=res.quot);
112 
113  if (sign<0)
114  *wstr++='-';
115 
116  *wstr='\0';
117 
118  // Reverse string
119  strreverse(str, wstr-1);
120 }
121 
122 void ultoa(unsigned long value, char * str, int base)
123 {
124  char* wstr = str;
125  div_t res;
126 
127  // Validate base
128  if (base<2 || base>35)
129  {
130  *wstr='\0';
131  return;
132  }
133 
134  // Conversion. Number is reversed.
135  do
136  {
137  res = div(value,base);
138  *wstr++ = num[res.rem];
139  } while (value=res.quot);
140 
141  *wstr='\0';
142 
143  // Reverse string
144  strreverse(str, wstr-1);
145 }
div_t
Definition: stdlib.h:61
strreverse
void strreverse(char *begin, char *end)
Definition: nonstdlib.cpp:21
nonstdlib.h
Provides common C functions that are not part of stdlib.h but the Arduino depends upon.