OSDN Git Service

2013.10.24
[uclinux-h8/uClinux-dist.git] / freeswan / lib / ultot.c
1 /*
2  * convert unsigned long to text
3  * Copyright (C) 2000  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: ultot.c,v 1.1 2000/08/16 23:07:16 henry Exp $
16  */
17 #include "internal.h"
18 #include "freeswan.h"
19
20 /*
21  - ultot - convert unsigned long to text
22  */
23 size_t                          /* length required for full conversion */
24 ultot(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 #       define  HEX32   (32/4)
36
37         p = bufend;
38         *--p = '\0';
39         switch (base) {
40         case 10:
41         case 'd':
42                 do {
43                         *--p = n%10 + '0';
44                         n /= 10;
45                 } while (n != 0);
46                 break;
47         case 16:
48         case 17:
49         case 'x':
50                 do {
51                         *--p = hex[n&0xf];
52                         n >>= 4;
53                 } while (n != 0);
54                 if (base == 17)
55                         while (bufend - p < HEX32 + 1)
56                                 *--p = '0';
57                 if (base == 'x') {
58                         *--p = 'x';
59                         *--p = '0';
60                 }
61                 break;
62         case 8:
63         case 'o':
64                 do {
65                         *--p = (n&07) + '0';
66                         n >>= 3;
67                 } while (n != 0);
68                 if (base == 'o')
69                         *--p = '0';
70                 break;
71         default:
72                 return 0;
73                 break;
74         }
75
76         len = bufend - p;
77         if (dstlen > 0) {
78                 if (len > dstlen)
79                         *(p + dstlen - 1) = '\0';
80                 strcpy(dst, p);
81         }
82         return len;
83 }