OSDN Git Service

2013.10.24
[uclinux-h8/uClinux-dist.git] / freeswan / lib / ultoa.c
1 /*
2  * convert unsigned long to ASCII
3  * Copyright (C) 1998, 1999  Henry Spencer.
4  * 
5  * This library is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU Library General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or (at your
8  * option) any later version.  See <http://www.fsf.org/copyleft/lgpl.txt>.
9  * 
10  * This library is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
13  * License for more details.
14  *
15  * RCSID $Id: ultoa.c,v 1.6 1999/10/13 18:09:06 henry Exp $
16  */
17 #include "internal.h"
18 #include "freeswan.h"
19
20 /*
21  - ultoa - convert unsigned long to decimal ASCII
22  */
23 size_t                          /* length required for full conversion */
24 ultoa(n, base, dst, dstlen)
25 unsigned long n;
26 int base;
27 char *dst;                      /* need not be valid if dstlen is 0 */
28 size_t dstlen;
29 {
30         char buf[3*sizeof(unsigned long) + 1];
31         char *bufend = buf + sizeof(buf);
32         size_t len;
33         char *p;
34         static char hex[] = "0123456789abcdef";
35
36         p = bufend;
37         *--p = '\0';
38         if (base == 10) {
39                 do {
40                         *--p = n%10 + '0';
41                         n /= 10;
42                 } while (n != 0);
43         } else if (base == 16) {
44                 do {
45                         *--p = hex[n&0xf];
46                         n >>= 4;
47                 } while (n != 0);
48                 *--p = 'x';
49                 *--p = '0';
50         } else if (base == 8) {
51                 do {
52                         *--p = (n&07) + '0';
53                         n >>= 3;
54                 } while (n != 0);
55                 *--p = '0';
56         } else
57                 *--p = '?';
58
59         len = bufend - p;
60
61         if (dstlen > 0) {
62                 if (len > dstlen)
63                         *(p + dstlen - 1) = '\0';
64                 strcpy(dst, p);
65         }
66         return len;
67 }