Skip to content

Instantly share code, notes, and snippets.

@giorgi568
Created August 9, 2024 14:32
Show Gist options
  • Save giorgi568/e72724d5f97e071537f504bad22e4332 to your computer and use it in GitHub Desktop.
Save giorgi568/e72724d5f97e071537f504bad22e4332 to your computer and use it in GitHub Desktop.
the c programming language book, exercise 3-5
#include <stdio.h>
/*
itob(n,s,b) converts the integer n into a base
b character representation in the string s.
b could be up to 36. after that we run out of letters.
*/
void itob(int n, char h[], int b);
void reverse(char s[], int len);
void main() {
char h[100];
itob(3552353, h, 36);
printf("%s\n", h);
}
void itob(int n, char h[], int b) {
int i, rem, len;
i = 0;
while (n != 0) {
rem = n % b;
if(rem <= 9) {
h[i++] = rem + '0';
}else {
h[i++] = rem + '0' + 7;
}
n /= b;
}
h[i] = '\0';
reverse(h, i);
}
void reverse(char s[], int len) {
int c, i, j;
for ( i = 0, j = len - 1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment