C++ fast division/mod by 10^x

后端 未结 10 650
我寻月下人不归
我寻月下人不归 2020-12-03 05:13

In my program I use a lot of integer division by 10^x and integer mod function of power 10.

For example:

unsigned __int64 a = 12345;
a = a / 100;
...         


        
10条回答
  •  感动是毒
    2020-12-03 05:30

    This is great for environments that lack any div operation and its only ~2x slower than native division on my i7 (optimizations off, naturally).

    Here's a slightly faster version of the algorithm, though there are still some nasty rounding errors with negative numbers.

    static signed Div10(signed n)
    {
        n = (n >> 1) + (n >> 2);
        n += n < 0 ? 9 : 2;
        n = n + (n >> 4);
        n = n + (n >> 8);
        n = n + (n >> 16);
        n = n >> 3;
        return n;
    }
    

    Since this method is for 32-bit integer precision, you can optimize away most of these shifts if you're working in an 8-bit or 16-bit environment.

提交回复
热议问题