-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathDigitCounter.h
More file actions
44 lines (35 loc) · 993 Bytes
/
DigitCounter.h
File metadata and controls
44 lines (35 loc) · 993 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#pragma once
#include <cstdint>
#include <limits>
#include <type_traits>
namespace OpenShock::Util {
template<typename T>
inline constexpr int Digits10CountMax = std::numeric_limits<T>::digits10 + (std::is_signed_v<T> ? 2 : 1);
template<typename T>
constexpr std::size_t Digits10Count(T val)
{
using Decayed = std::remove_cv_t<std::remove_reference_t<T>>;
static_assert(std::is_integral_v<Decayed>);
using U = std::make_unsigned_t<Decayed>;
std::size_t digits = 1;
U u;
if constexpr (std::is_signed_v<Decayed>) {
if (val < 0) {
// Account for the sign
digits++;
// Safe magnitude via unsigned modular negation
u = U(0) - static_cast<U>(val);
} else {
u = static_cast<U>(val);
}
} else {
u = static_cast<U>(val);
}
// Now count digits of u (magnitude), base-10
while (u >= 10) {
u /= 10;
digits++;
}
return digits;
}
} // namespace OpenShock::Util