long2str.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 *
  15. long2str(val, base)
  16. register long val;
  17. register base;
  18. {
  19. static char numbuf[MAXWIDTH];
  20. static char vec[] = "0123456789ABCDEF";
  21. register char *p = &numbuf[MAXWIDTH];
  22. int sign = (base > 0);
  23. *--p = '\0'; /* null-terminate string */
  24. if (val) {
  25. if (base > 0) {
  26. if (val < 0L) {
  27. long v1 = -val;
  28. if (v1 == val)
  29. goto overflow;
  30. val = v1;
  31. }
  32. else
  33. sign = 0;
  34. }
  35. else
  36. if (base < 0) { /* unsigned */
  37. base = -base;
  38. if (val < 0L) { /* taken from Amoeba src */
  39. register mod, i;
  40. overflow:
  41. mod = 0;
  42. for (i = 0; i < 8 * sizeof val; i++) {
  43. mod <<= 1;
  44. if (val < 0)
  45. mod++;
  46. val <<= 1;
  47. if (mod >= base) {
  48. mod -= base;
  49. val++;
  50. }
  51. }
  52. *--p = vec[mod];
  53. }
  54. }
  55. do {
  56. *--p = vec[(int) (val % base)];
  57. val /= base;
  58. } while (val != 0L);
  59. if (sign)
  60. *--p = '-'; /* don't forget it !! */
  61. }
  62. else
  63. *--p = '0'; /* just a simple 0 */
  64. return p;
  65. }