Pristine Ack-5.5
[Ack-5.5.git] / modules / src / string / long2str.c
1 /* $Id: long2str.c,v 1.6 1994/06/24 11:22:36 ceriel Exp $ */
2 /*
3  * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
4  * See the copyright notice in the ACK home directory, in the file "Copyright".
5  */
6 /* Integer to String translator
7         -> base is a value from [-16,-2] V [2,16]
8         -> base < 0: see 'val' as unsigned value
9         -> no checks for buffer overflow and illegal parameters
10         (1985, EHB)
11 */
12
13 #include "ack_string.h"
14
15 #define MAXWIDTH 32
16
17 char *
18 long2str(val, base)
19         register long val;
20         register base;
21 {
22         static char numbuf[MAXWIDTH];
23         static char vec[] = "0123456789ABCDEF";
24         register char *p = &numbuf[MAXWIDTH];
25         int sign = (base > 0);
26
27         *--p = '\0';            /* null-terminate string        */
28         if (val) {
29                 if (base > 0) {
30                         if (val < 0L) {
31                                 long v1 = -val;
32                                 if (v1 == val)
33                                         goto overflow;
34                                 val = v1;
35                         }
36                         else
37                                 sign = 0;
38                 }
39                 else
40                 if (base < 0) {                 /* unsigned */
41                         base = -base;
42                         if (val < 0L) { /* taken from Amoeba src */
43                                 register mod, i;
44                         overflow:
45                                 mod = 0;
46                                 for (i = 0; i < 8 * sizeof val; i++) {
47                                         mod <<= 1;
48                                         if (val < 0)
49                                                 mod++;
50                                         val <<= 1;
51                                         if (mod >= base) {
52                                                 mod -= base;
53                                                 val++;
54                                         }
55                                 }
56                                 *--p = vec[mod];
57                         }
58                 }
59                 do {
60                         *--p = vec[(int) (val % base)];
61                         val /= base;
62                 } while (val != 0L);
63                 if (sign)
64                         *--p = '-';     /* don't forget it !!   */
65         }
66         else
67                 *--p = '0';             /* just a simple 0      */
68         return p;
69 }