Added padding and case selection to txNumber

This commit is contained in:
BlackMark 2019-08-03 19:49:01 +02:00
parent 8153696309
commit 6438aa81c1

View File

@ -22,11 +22,6 @@ static constexpr size_t cntDigits()
T num = limit;
size_t cnt = 0;
if (num < 0) {
num = -num;
++cnt;
}
do {
num /= Base;
++cnt;
@ -38,8 +33,23 @@ static constexpr size_t cntDigits()
template <typename T, size_t Base>
static constexpr size_t maxNumDigits()
{
T minDigits = cntDigits<T, util::NumericLimits<T>::min(), Base>();
T maxDigits = cntDigits<T, util::NumericLimits<T>::max(), Base>();
constexpr T minVal = util::NumericLimits<T>::min();
constexpr T maxVal = util::NumericLimits<T>::max();
T minDigits = cntDigits<T, minVal, Base>() + ((minVal < 0) ? 1 : 0);
T maxDigits = cntDigits<T, maxVal, Base>() + ((maxVal < 0) ? 1 : 0);
return (minDigits < maxDigits) ? maxDigits : minDigits;
}
template <typename T, size_t Base>
static constexpr size_t maxPadding()
{
constexpr T minVal = util::NumericLimits<T>::min();
constexpr T maxVal = util::NumericLimits<T>::max();
T minDigits = cntDigits<T, minVal, Base>();
T maxDigits = cntDigits<T, maxVal, Base>();
return (minDigits < maxDigits) ? maxDigits : minDigits;
}
@ -111,14 +121,17 @@ class Uart {
txByte(ch);
}
template <typename T, size_t Base = 10>
template <typename T, size_t Base = 10, size_t Padding = 0, char PadChar = '0', bool LowerCase = true>
static void txNumber(const T &val)
{
static_assert(util::is_integral_v<T>, "Only supported on integral types");
static_assert(Base >= 2, "Numbers with bases less than 2 make no sense");
static_assert(Base <= 16, "Numbers with bases higher than 16 are not supported");
static_assert(Padding <= detail::maxPadding<T, Base>(), "Cannot pad more than maximum length of number");
constexpr char alphaChar = (LowerCase) ? 'a' : 'A';
constexpr size_t numDigits = detail::maxNumDigits<T, Base>();
data_t buffer[numDigits];
data_t *bufEnd = buffer + numDigits - 1;
@ -131,10 +144,20 @@ class Uart {
do {
data_t lastDigit = digits % Base;
*bufEnd-- = (lastDigit < 10) ? ('0' + lastDigit) : ('a' + lastDigit - 10);
*bufEnd-- = (lastDigit < 10) ? ('0' + lastDigit) : (alphaChar + lastDigit - 10);
digits /= Base;
} while (digits > 0);
if (Padding > 0) {
size_t strLen = buffer + numDigits - (bufEnd + 1);
if (Padding > strLen) {
for (size_t i = Padding; i > strLen && bufEnd >= buffer; --i) {
*bufEnd-- = PadChar;
}
}
}
for (data_t *buf = bufEnd + 1; buf < buffer + numDigits; ++buf)
txByte(*buf);
}