khalfella

ansi_c_pg059_ch03_ex05.c

Dec 27th, 2014
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. /*
  2. * Exercise 3-5.
  3. * Write the function itob(n,s,b) that converts the integer n into a base b
  4. * character representation in the string s. In particular, itob(n,s,16)
  5. * formats s as a hexadecimal integer in s.
  6. */
  7.  
  8.  
  9.  
  10. #include <stdio.h>
  11. #include <string.h>
  12. /* reverse: reverse string s in place */
  13. void
  14. reverse(char s[])
  15. {
  16. int c, i, j;
  17. for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
  18. c = s[i];
  19. s[i] = s[j];
  20. s[j] = c;
  21. }
  22. }
  23.  
  24.  
  25. void
  26. itoa(int n, char s[],unsigned int b)
  27. {
  28. int i, sign;
  29. unsigned int un = n;
  30. char c;
  31. if ((sign = n) < 0) /* record sign */
  32. un = -n; /* make n positive */
  33. i = 0;
  34. do {
  35. if ((c = (un % b)) <= 9) {
  36. c = c + '0';
  37. } else {
  38. c = c - 10 + 'a';
  39. }
  40.  
  41. s[i++] = c; /* getnextdigit */
  42. } while ((un /= b) > 0);
  43. if (sign < 0)
  44. s[i++] = '-';
  45. s[i] = '\0';
  46. reverse(s);
  47. }
  48.  
  49. int
  50. main(int argc, char **argv)
  51. {
  52. char s[100];
  53. itoa(108, s, 16);
  54. printf("%s\n", s);
  55. return (0);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment