long2str.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* $Header$ */
  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. #define MAXWIDTH 32
  13. char *
  14. long2str(val, base)
  15. register long val;
  16. register base;
  17. {
  18. static char numbuf[MAXWIDTH];
  19. static char vec[] = "0123456789ABCDEF";
  20. register char *p = &numbuf[MAXWIDTH];
  21. int sign = (base > 0);
  22. *--p = '\0'; /* null-terminate string */
  23. if (val) {
  24. if (base > 0) {
  25. if (val < 0L) {
  26. if ((val = -val) < 0L)
  27. goto overflow;
  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. }