Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdarg.h>
- static void
- itoa (char *buf, int base, int d)
- {
- char *p = buf;
- char *p1, *p2;
- unsigned int ud = d;
- int divisor = 10;
- if (base == 'd' && d < 0)
- {
- *p++ = '-';
- buf++;
- ud = -d;
- }
- else if (base == 'x')
- divisor = 16;
- do
- {
- int remainder = ud % divisor;
- *p++ = (remainder < 10) ? remainder + '0' : remainder + 'a' - 10;
- }
- while (ud /= divisor);
- *p = 0;
- p1 = buf;
- p2 = p - 1;
- while (p1 < p2)
- {
- char tmp = *p1;
- *p1 = *p2;
- *p2 = tmp;
- p1++;
- p2--;
- }
- }
- /* Format a string and print it on the screen, just like the libc
- function printf. */
- void
- printf (const char *format, ...)
- {
- int c;
- char buf[20];
- va_list arg;
- va_start(arg, format);
- while ((c = *format++) != 0)
- {
- if (c != '%')
- putchar (c);
- else
- {
- char *p, *p2;
- int pad0 = 0, pad = 0;
- c = *format++;
- if (c == '0')
- {
- pad0 = 1;
- c = *format++;
- }
- if (c >= '0' && c <= '9')
- {
- pad = c - '0';
- c = *format++;
- }
- switch (c)
- {
- case 'd':
- case 'u':
- case 'x':
- itoa (buf, c, va_arg(arg, int));
- p = buf;
- goto string;
- break;
- case 's':
- p = va_arg(arg, char *);
- if (! p)
- p = "(null)";
- string:
- for (p2 = p; *p2; p2++);
- for (; p2 < p + pad; p2++)
- putchar (pad0 ? '0' : ' ');
- while (*p)
- putchar (*p++);
- break;
- default:
- putchar (va_arg(arg, int));
- break;
- }
- }
- }
- va_end(arg);
- }
Add Comment
Please, Sign In to add comment