-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhex_conversion.cpp
More file actions
54 lines (39 loc) · 847 Bytes
/
hex_conversion.cpp
File metadata and controls
54 lines (39 loc) · 847 Bytes
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
/*
一道常见的面试题,进制转换,
例如:输入一个int型十进制数,以字符串形式输出一个十二进制数
*/
#include <iostream>
void reverse_string(char *s)
{
int ptr_start = 0;
int ptr_end = strlen(s) - 1;
char tmp;
while(ptr_start <= ptr_end - 1) {
//swap
tmp = s[ptr_start];
s[ptr_start] = s[ptr_end];
s[ptr_end] = tmp;
ptr_start ++;
ptr_end --;
}
}
char *convert(int in, int jinzhi)
{
char *result = (char *)malloc(64);
memset(result, 0, 64);
int i = 0;
while(in)
{
sprintf(result + i, "%x", in % jinzhi);
in = in / jinzhi;
i ++;
}
reverse_string(result);
return result;
}
int main()
{
char* result = convert(200, 16);
printf("result: %s\n", result);
return 0;
}