Commit | Line | Data |
---|---|---|
0bdacbe1 AM |
1 | /* File : int2str.c |
2 | Author : Richard A. O'Keefe | |
3 | Updated: 6 February 1993 | |
4 | Defines: int2str() | |
5 | ||
6 | int2str(dst, radix, val) | |
7 | converts the (long) integer "val" to character form and moves it to | |
8 | the destination string "dst" followed by a terminating NUL. The | |
9 | result is normally a pointer to this NUL character, but if the radix | |
10 | is dud the result will be NullS and nothing will be changed. | |
11 | ||
12 | If radix is -2..-36, val is taken to be SIGNED. | |
13 | If radix is 2.. 36, val is taken to be UNSIGNED. | |
14 | That is, val is signed if and only if radix is. You will normally | |
15 | use radix -10 only through itoa and ltoa, for radix 2, 8, or 16 | |
16 | unsigned is what you generally want. | |
17 | */ | |
18 | ||
19 | static char dig_vec[] = | |
20 | "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
21 | ||
22 | ||
23 | char *int2str(dst, radix, val) | |
24 | register char *dst; | |
25 | register int radix; | |
26 | register long val; | |
27 | { | |
28 | char buffer[65]; /* Ready for 64-bit machines */ | |
29 | register char *p; | |
30 | ||
31 | if (radix < 2 || radix > 36) { /* Not 2..36 */ | |
32 | if (radix > -2 || radix < -36) return (char *)0; | |
33 | if (val < 0) { | |
34 | *dst++ = '-'; | |
35 | val = -val; | |
36 | } | |
37 | radix = -radix; | |
38 | } | |
39 | /* The slightly contorted code which follows is due to the | |
40 | fact that few machines directly support unsigned long / and %. | |
41 | Certainly the VAX C compiler generates a subroutine call. In | |
42 | the interests of efficiency (hollow laugh) I let this happen | |
43 | for the first digit only; after that "val" will be in range so | |
44 | that signed integer division will do. Sorry 'bout that. | |
45 | CHECK THE CODE PRODUCED BY YOUR C COMPILER. The first % and / | |
46 | should be unsigned, the second % and / signed, but C compilers | |
47 | tend to be extraordinarily sensitive to minor details of style. | |
48 | This works on a VAX, that's all I claim for it. | |
49 | */ | |
50 | p = &buffer[sizeof buffer]; | |
51 | *--p = '\0'; | |
52 | *--p = dig_vec[(unsigned long)val%(unsigned long)radix]; | |
53 | val = (unsigned long)val/(unsigned long)radix; | |
54 | while (val != 0) *--p = dig_vec[val%radix], val /= radix; | |
55 | while (*dst++ = *p++) ; | |
56 | return dst-1; | |
57 | } | |
58 |