long2str.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* $Id$ */
  2. /*
  3. * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
  4. * See the copyright notice in the ACK home directory, in the file "Copyright".
  5. */
  6. /* Integer to String translator
  7. -> base is a value from [-16,-2] V [2,16]
  8. -> base < 0: see 'val' as unsigned value
  9. -> no checks for buffer overflow and illegal parameters
  10. (1985, EHB)
  11. */
  12. #include "ack_string.h"
  13. #define MAXWIDTH 32
  14. char *long2str(long val, int base)
  15. {
  16. static char numbuf[MAXWIDTH];
  17. static char vec[] = "0123456789ABCDEF";
  18. register char *p = &numbuf[MAXWIDTH];
  19. int sign = (base > 0);
  20. *--p = '\0'; /* null-terminate string */
  21. if (val) {
  22. if (base > 0) {
  23. if (val < 0L) {
  24. long v1 = -val;
  25. if (v1 == val)
  26. goto overflow;
  27. val = v1;
  28. }
  29. else
  30. sign = 0;
  31. }
  32. else
  33. if (base < 0) { /* unsigned */
  34. base = -base;
  35. if (val < 0L) { /* taken from Amoeba src */
  36. register mod, i;
  37. overflow:
  38. mod = 0;
  39. for (i = 0; i < 8 * sizeof val; i++) {
  40. mod <<= 1;
  41. if (val < 0)
  42. mod++;
  43. val <<= 1;
  44. if (mod >= base) {
  45. mod -= base;
  46. val++;
  47. }
  48. }
  49. *--p = vec[mod];
  50. }
  51. }
  52. do {
  53. *--p = vec[(int) (val % base)];
  54. val /= base;
  55. } while (val != 0L);
  56. if (sign)
  57. *--p = '-'; /* don't forget it !! */
  58. }
  59. else
  60. *--p = '0'; /* just a simple 0 */
  61. return p;
  62. }