atoi.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #pragma once
  2. #include <nall/stdint.hpp>
  3. namespace nall {
  4. constexpr inline auto toBinary_(const char* s, uintmax sum = 0) -> uintmax {
  5. return (
  6. *s == '0' || *s == '1' ? toBinary_(s + 1, (sum << 1) | *s - '0') :
  7. *s == '\'' ? toBinary_(s + 1, sum) :
  8. sum
  9. );
  10. }
  11. constexpr inline auto toOctal_(const char* s, uintmax sum = 0) -> uintmax {
  12. return (
  13. *s >= '0' && *s <= '7' ? toOctal_(s + 1, (sum << 3) | *s - '0') :
  14. *s == '\'' ? toOctal_(s + 1, sum) :
  15. sum
  16. );
  17. }
  18. constexpr inline auto toDecimal_(const char* s, uintmax sum = 0) -> uintmax {
  19. return (
  20. *s >= '0' && *s <= '9' ? toDecimal_(s + 1, (sum * 10) + *s - '0') :
  21. *s == '\'' ? toDecimal_(s + 1, sum) :
  22. sum
  23. );
  24. }
  25. constexpr inline auto toHex_(const char* s, uintmax sum = 0) -> uintmax {
  26. return (
  27. *s >= 'A' && *s <= 'F' ? toHex_(s + 1, (sum << 4) | *s - 'A' + 10) :
  28. *s >= 'a' && *s <= 'f' ? toHex_(s + 1, (sum << 4) | *s - 'a' + 10) :
  29. *s >= '0' && *s <= '9' ? toHex_(s + 1, (sum << 4) | *s - '0') :
  30. *s == '\'' ? toHex_(s + 1, sum) :
  31. sum
  32. );
  33. }
  34. //
  35. constexpr inline auto toBinary(const char* s) -> uintmax {
  36. return (
  37. *s == '0' && (*(s + 1) == 'B' || *(s + 1) == 'b') ? toBinary_(s + 2) :
  38. *s == '%' ? toBinary_(s + 1) : toBinary_(s)
  39. );
  40. }
  41. constexpr inline auto toOctal(const char* s) -> uintmax {
  42. return (
  43. *s == '0' && (*(s + 1) == 'O' || *(s + 1) == 'o') ? toOctal_(s + 2) :
  44. toOctal_(s)
  45. );
  46. }
  47. constexpr inline auto toHex(const char* s) -> uintmax {
  48. return (
  49. *s == '0' && (*(s + 1) == 'X' || *(s + 1) == 'x') ? toHex_(s + 2) :
  50. *s == '$' ? toHex_(s + 1) : toHex_(s)
  51. );
  52. }
  53. //
  54. constexpr inline auto toNatural(const char* s) -> uintmax {
  55. return (
  56. *s == '0' && (*(s + 1) == 'B' || *(s + 1) == 'b') ? toBinary_(s + 2) :
  57. *s == '0' && (*(s + 1) == 'O' || *(s + 1) == 'o') ? toOctal_(s + 2) :
  58. *s == '0' && (*(s + 1) == 'X' || *(s + 1) == 'x') ? toHex_(s + 2) :
  59. *s == '%' ? toBinary_(s + 1) : *s == '$' ? toHex_(s + 1) : toDecimal_(s)
  60. );
  61. }
  62. constexpr inline auto toInteger(const char* s) -> intmax {
  63. return (
  64. *s == '+' ? +toNatural(s + 1) : *s == '-' ? -toNatural(s + 1) : toNatural(s)
  65. );
  66. }
  67. //
  68. inline auto toReal(const char* s) -> double {
  69. return atof(s);
  70. }
  71. }