Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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 <stdio.h>
- #include <string.h>
- /* reverse: reverse 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;
- }
- }
- void
- itoa(int n, char s[],unsigned int b)
- {
- int i, sign;
- unsigned int un = n;
- char c;
- if ((sign = n) < 0) /* record sign */
- un = -n; /* make n positive */
- i = 0;
- do {
- if ((c = (un % b)) <= 9) {
- c = c + '0';
- } else {
- c = c - 10 + 'a';
- }
- s[i++] = c; /* getnextdigit */
- } while ((un /= b) > 0);
- if (sign < 0)
- s[i++] = '-';
- s[i] = '\0';
- reverse(s);
- }
- int
- main(int argc, char **argv)
- {
- char s[100];
- itoa(108, s, 16);
- printf("%s\n", s);
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment