Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_3.5_itob.c
1240 views
1
/* function itob(n,s,b), that converts the integer n into a base b character representation in
2
the string s.
3
*/
4
#include<stdio.h>
5
#include<string.h>
6
7
#define MAXLINE 100
8
9
void itob(int n,char s[],int b);
10
void reverse(char s[]);
11
12
int main(void)
13
{
14
int number,base;
15
char str[MAXLINE];
16
17
number=42425;
18
base=16;
19
20
itob(number,str,base);
21
22
printf("%s",str);
23
24
return 0;
25
}
26
27
void itob(int n,char s[],int b)
28
{
29
int i,j,sign;
30
31
if((sign=n)<0)
32
n = -n;
33
34
i = 0;
35
36
do
37
{
38
j = n % b;
39
40
s[i++] = (j <= 9)?j+'0':j+'a'-10;
41
}while((n/=b)>0);
42
43
if(sign < 0)
44
s[i++]='-';
45
46
s[i]='\0';
47
48
reverse(s);
49
}
50
51
void reverse(char s[])
52
{
53
int i,j,c;
54
55
for(i=0,j=strlen(s)-1;i<j;i++,j--)
56
c=s[i],s[i]=s[j],s[j]=c;
57
}
58
59
60