blob: e7b4d3e158910eb67ae00a25cd458adb4d92fc34 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
#include <stdio.h>
#define MAXLEN 15
void reverse(char str[]);
char* itob(int n, char str[], int base);
int
main(void)
{
int n = 21474836;
char str[MAXLEN];
printf("%x\n", n);
printf("%s\n", itob(n, str, 16));
return 0;
}
void
reverse(char str[])
{
int i, j;
char temp;
for (j = 0; str[j] != '\0'; j++)
;
for (i = 0, --j; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
char*
itob(int n, char str[], int base)
{
int sign, i;
/* to include the most -ve int */
n = ((sign = n) < 0) ? -(n+1) : n-1;
i = 0;
do {
if (n%base >= 0 && n%base <= 9)
str[i++] = n%base + '0';
else
str[i++] = n%base + 'a' - 10;
} while ((n /= base) > 0);
if (sign <0)
str[i++] = '-';
/* part of "to include the most -ve int" */
str[0] += 1;
str[i] = '\0';
reverse(str);
return str;
}
|