to_text_int.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // $Id$
  3. //
  4. #include<__vic/to_text.h>
  5. #include<__vic/stdint.h>
  6. namespace __vic {
  7. //----------------------------------------------------------------------------
  8. template<class UInt>
  9. inline void append_unsigned_integer(UInt n, std::string &s)
  10. {
  11. if(n == UInt(0))
  12. {
  13. s += '0';
  14. return;
  15. }
  16. char buf[sizeof(n) * 4]; // *3 would be enough but I prefer aligned bufs
  17. char *p = buf + sizeof buf;
  18. do {
  19. *--p = char(n % 10) + '0';
  20. n /= 10;
  21. } while(n);
  22. s.append(p, buf + sizeof buf - p);
  23. }
  24. //----------------------------------------------------------------------------
  25. template<class Int>
  26. inline void append_signed_integer(Int n, std::string &s)
  27. {
  28. typedef typename uint_exactly_bytes<sizeof(Int)>::type UInt;
  29. UInt uint_value;
  30. if(n < Int(0))
  31. {
  32. s += '-';
  33. // two's complement representation is implied
  34. uint_value = UInt(~n) + UInt(1);
  35. }
  36. else uint_value = n;
  37. append_unsigned_integer(uint_value, s);
  38. }
  39. //----------------------------------------------------------------------------
  40. void to_text_append(long n, std::string &s)
  41. {
  42. append_signed_integer(n, s);
  43. }
  44. //----------------------------------------------------------------------------
  45. void to_text_append(unsigned long n, std::string &s)
  46. {
  47. append_unsigned_integer(n, s);
  48. }
  49. //----------------------------------------------------------------------------
  50. #ifdef __VIC_LONGLONG
  51. void to_text_append(__VIC_LONGLONG n, std::string &s)
  52. {
  53. append_signed_integer(n, s);
  54. }
  55. //----------------------------------------------------------------------------
  56. void to_text_append(unsigned __VIC_LONGLONG n, std::string &s)
  57. {
  58. append_unsigned_integer(n, s);
  59. }
  60. #endif
  61. //----------------------------------------------------------------------------
  62. } // namespace