Skip to content

Instantly share code, notes, and snippets.

@yhafri
Forked from markpapadakis/todigits.cpp
Created June 21, 2020 09:41
Show Gist options
  • Save yhafri/cf8c6add7955a0532b2f5b755e53a046 to your computer and use it in GitHub Desktop.
Save yhafri/cf8c6add7955a0532b2f5b755e53a046 to your computer and use it in GitHub Desktop.
static uint8_t DigitsCount(uint64_t v)
{
for (uint8_t res{1}; ;res+=4, v/=10000U)
{
if (likely(v < 10)) return res;
if (likely(v < 100)) return res + 1;
if (likely(v < 1000)) return res + 2;
if (likely(v < 10000)) return res + 3;
}
}
uint8_t U32ToASCII(uint32_t v, char *const dst)
{
const auto result = DigitsCount(v);
uint32_t pos = result - 1;
while (v >= 10)
{
const auto q = v / 10;
const auto r = static_cast<uint32_t>(v % 10);
dst[pos--] = '0' + r;
v = q;
}
dst[pos] = static_cast<uint32_t>(v) + '0';
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment