Mercurial > hg > toybox
comparison lib/lib.c @ 1042:cbc467592b2e draft
Remove itoa/utoa, let libc do this with sprintf.
author | Rob Landley <rob@landley.net> |
---|---|
date | Tue, 03 Sep 2013 08:30:47 -0500 |
parents | 9686469a857a |
children | acf7bb2b99e2 |
comparison
equal
deleted
inserted
replaced
1041:d3f9e55e350a | 1042:cbc467592b2e |
---|---|
173 path++; | 173 path++; |
174 } | 174 } |
175 free(cwd); | 175 free(cwd); |
176 | 176 |
177 return rlist; | 177 return rlist; |
178 } | |
179 | |
180 // Convert unsigned int to ascii, writing into supplied buffer. A truncated | |
181 // result contains the first few digits of the result ala strncpy, and is | |
182 // always null terminated (unless buflen is 0). | |
183 void utoa_to_buf(unsigned n, char *buf, unsigned buflen) | |
184 { | |
185 int i, out = 0; | |
186 | |
187 if (buflen) { | |
188 for (i=1000000000; i; i/=10) { | |
189 int res = n/i; | |
190 | |
191 if ((res || out || i == 1) && --buflen>0) { | |
192 out++; | |
193 n -= res*i; | |
194 *buf++ = '0' + res; | |
195 } | |
196 } | |
197 *buf = 0; | |
198 } | |
199 } | |
200 | |
201 // Convert signed integer to ascii, using utoa_to_buf() | |
202 void itoa_to_buf(int n, char *buf, unsigned buflen) | |
203 { | |
204 if (buflen && n<0) { | |
205 n = -n; | |
206 *buf++ = '-'; | |
207 buflen--; | |
208 } | |
209 utoa_to_buf((unsigned)n, buf, buflen); | |
210 } | |
211 | |
212 // This static buffer is used by both utoa() and itoa(), calling either one a | |
213 // second time will overwrite the previous results. | |
214 // | |
215 // The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes. | |
216 // Note that int is always 32 bits on any remotely unix-like system, see | |
217 // http://www.unix.org/whitepapers/64bit.html for details. | |
218 | |
219 static char itoa_buf[12]; | |
220 | |
221 // Convert unsigned integer to ascii, returning a static buffer. | |
222 char *utoa(unsigned n) | |
223 { | |
224 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf)); | |
225 | |
226 return itoa_buf; | |
227 } | |
228 | |
229 char *itoa(int n) | |
230 { | |
231 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf)); | |
232 | |
233 return itoa_buf; | |
234 } | 178 } |
235 | 179 |
236 // atol() with the kilo/mega/giga/tera/peta/exa extensions. | 180 // atol() with the kilo/mega/giga/tera/peta/exa extensions. |
237 // (zetta and yotta don't fit in 64 bits.) | 181 // (zetta and yotta don't fit in 64 bits.) |
238 long atolx(char *numstr) | 182 long atolx(char *numstr) |