Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created November 12, 2009 06:13
Show Gist options
  • Save shaobin0604/232647 to your computer and use it in GitHub Desktop.
Save shaobin0604/232647 to your computer and use it in GitHub Desktop.
/*
* Exercise 3-5. 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 s as a hexadecimal integer in s.
*/
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#define abs(x) ((x) > 0) ? (x) : -(x)
#define MAX_LEN 50
void itob(int n, char s[], int b);
void reverse(char s[]);
int main(void) {
char buffer[MAX_LEN];
int i;
for ( i = 2; i <= 36; ++i ) {
itob(INT_MIN, buffer, i);
printf("Decimal %d in base %-2d : %s\n", INT_MIN, i, buffer);
}
return 0;
}
/* Stores a string representation of integer n
in s[], using a numerical base of b. Will handle
up to base-36 before we run out of digits to use. */
void itob(int n, char s[], int b) {
static char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i, sign;
if ( b < 2 || b > 36 ) {
fprintf(stderr, "EX3_5: Cannot support base %d\n", b);
exit(EXIT_FAILURE);
}
sign = n;
i = 0;
do {
s[i++] = digits[abs(n % b)];
} while ((n /= b) != 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* Reverses string s[] in place */
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment