ultostr.c 804 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /*
  2. * Copyright (C) 2000 Manuel Novoa III
  3. *
  4. * Note: buf is a pointer to the END of the buffer passed.
  5. * Call like this;
  6. * char buf[SIZE], *p;
  7. * p = __ultostr(buf + sizeof(buf) - 1, ...)
  8. *
  9. * For longs of 32 bits, appropriate buffer sizes are:
  10. * base = 2 33 = 32 digits + 1 nul
  11. * base = 10 11 = 10 digits + 1 nul
  12. * base = 16 9 = 8 hex digits + 1 nul
  13. */
  14. char *__ultostr(char *buf, unsigned long uval, int base, int uppercase)
  15. {
  16. int digit;
  17. if ((base < 2) || (base > 36)) {
  18. return 0;
  19. }
  20. *buf = '\0';
  21. do {
  22. digit = uval % base;
  23. uval /= base;
  24. /* note: slightly slower but generates less code */
  25. *--buf = '0' + digit;
  26. if (digit > 9) {
  27. *buf = (uppercase ? 'A' : 'a') + digit - 10;
  28. }
  29. } while (uval);
  30. return buf;
  31. }