Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out the number of digits of min/max values of an integral type at compile time

Is there a way to find out the number of digits of min/max values of an integral type at compile time so that it's suitable to be placed as a template parameter?

Ideally, there will be an existing solution in, for example, Boost MPL. Failing that I'm looking for some pointers for a hand-coded solution.

like image 472
Alex B Avatar asked Dec 30 '25 19:12

Alex B


2 Answers

Is this what you are looking for?

std::numeric_limits<T>::digits10

Number of digits (in decimal base) that can be represented without change.

like image 162
R Samuel Klatchko Avatar answered Jan 01 '26 11:01

R Samuel Klatchko


Works with any value you can provide as an unsigned long template argument, in any base:

template<unsigned B, unsigned long N>
struct base_digits_detail {
  enum { result = 1 + base_digits_detail<B, N/B>::result };
};
template<unsigned B>
struct base_digits_detail<B, 0> {
private:
  enum { result = 0 };

  template<unsigned, unsigned long>
  friend class base_digits_detail;
};

template<unsigned B, unsigned long N>
struct base_digits {
  enum { result = base_digits_detail<B, N>::result };
};
template<unsigned B>
struct base_digits<B, 0> {
  enum { result = 1 };
};

Test

#include <climits>
#include <iostream>
int main() {
  std::cout << base_digits<10, 0>::result << '\n';
  std::cout << base_digits<10, 1>::result << '\n';
  std::cout << base_digits<10, 10>::result << '\n';
  std::cout << base_digits<10, 100>::result << '\n';
  std::cout << base_digits<10, 1000>::result << '\n';
  std::cout << base_digits<10, UINT_MAX>::result << '\n';
  std::cout << '\n';
  std::cout << base_digits<8, 0>::result << '\n';
  std::cout << base_digits<8, 01>::result << '\n';
  std::cout << base_digits<8, 010>::result << '\n';
  std::cout << base_digits<8, 0100>::result << '\n';
  std::cout << base_digits<8, 01000>::result << '\n';
  std::cout << base_digits<8, UINT_MAX>::result << '\n';

  return 0;
}

Output

1
1
2
3
4
10

1
1
2
3
4
11

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!