Skip to content

Instantly share code, notes, and snippets.

@markpapadakis
Created May 5, 2015 21:22
Show Gist options
  • Select an option

  • Save markpapadakis/d44eb8b53071a1390dbc to your computer and use it in GitHub Desktop.

Select an option

Save markpapadakis/d44eb8b53071a1390dbc to your computer and use it in GitHub Desktop.

Revisions

  1. markpapadakis created this gist May 5, 2015.
    27 changes: 27 additions & 0 deletions todigits.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    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;
    }