Page 64
Write the function itob(n,s,b)
that converts the integer n
into a base b
character representation in the string s
. In particular, itob(n,s,16)
formats n
as a hexadecimal integer in s
.
#include <stdbool.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#define LEN 1000
void itob(int n, char s[], int b);
void reverse(char s[]);
int main()
{
char s[LEN];
itob(254, s, 16);
printf("%s", s);
}
void itob(int n, char s[], int b)
{
int i, val, sign;
if ((sign = n) < 0)
n = -n;
i = 0;
do {
val = n % b;
s[i++] = val <= 9 ? (val + '0') : (val - 10 + 'a');
} while ((n /= b) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
void reverse(char s[])
{
int c, i, j;
for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}