MichaelPetch

printf

Feb 3rd, 2021 (edited)
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. #include<stdarg.h>
  2.  
  3. static void
  4. itoa (char *buf, int base, int d)
  5. {
  6. char *p = buf;
  7. char *p1, *p2;
  8. unsigned int ud = d;
  9. int divisor = 10;
  10.  
  11.  
  12. if (base == 'd' && d < 0)
  13. {
  14. *p++ = '-';
  15. buf++;
  16. ud = -d;
  17. }
  18. else if (base == 'x')
  19. divisor = 16;
  20.  
  21. do
  22. {
  23. int remainder = ud % divisor;
  24.  
  25. *p++ = (remainder < 10) ? remainder + '0' : remainder + 'a' - 10;
  26. }
  27. while (ud /= divisor);
  28.  
  29. *p = 0;
  30.  
  31.  
  32. p1 = buf;
  33. p2 = p - 1;
  34. while (p1 < p2)
  35. {
  36. char tmp = *p1;
  37. *p1 = *p2;
  38. *p2 = tmp;
  39. p1++;
  40. p2--;
  41. }
  42. }
  43.  
  44. /* Format a string and print it on the screen, just like the libc
  45. function printf. */
  46. void
  47. printf (const char *format, ...)
  48. {
  49. int c;
  50. char buf[20];
  51.  
  52. va_list arg;
  53. va_start(arg, format);
  54.  
  55. while ((c = *format++) != 0)
  56. {
  57. if (c != '%')
  58. putchar (c);
  59. else
  60. {
  61. char *p, *p2;
  62. int pad0 = 0, pad = 0;
  63.  
  64. c = *format++;
  65. if (c == '0')
  66. {
  67. pad0 = 1;
  68. c = *format++;
  69. }
  70.  
  71. if (c >= '0' && c <= '9')
  72. {
  73. pad = c - '0';
  74. c = *format++;
  75. }
  76.  
  77. switch (c)
  78. {
  79. case 'd':
  80. case 'u':
  81. case 'x':
  82. itoa (buf, c, va_arg(arg, int));
  83. p = buf;
  84. goto string;
  85. break;
  86.  
  87. case 's':
  88. p = va_arg(arg, char *);
  89. if (! p)
  90. p = "(null)";
  91.  
  92. string:
  93. for (p2 = p; *p2; p2++);
  94. for (; p2 < p + pad; p2++)
  95. putchar (pad0 ? '0' : ' ');
  96. while (*p)
  97. putchar (*p++);
  98. break;
  99.  
  100. default:
  101. putchar (va_arg(arg, int));
  102. break;
  103. }
  104. }
  105. }
  106. va_end(arg);
  107. }
Add Comment
Please, Sign In to add comment