How does the GCC implementation of modulo (%) work, and why does it not use the div instruction?

前端 未结 2 945
-上瘾入骨i
-上瘾入骨i 2020-12-01 12:22

I was trying to work out how to calculate modulo 10 in assembly so i compiled the following c code in gcc to see what it came up with.

unsigned int i=999;
un         


        
2条回答
  •  一整个雨季
    2020-12-01 13:03

    The first part, up to shrl $3, %edx, implements a fast integer division by 10. There are a few different algorithms that work when the number by which you divide is known in advance. Note that 858993459 is "0.2 * 2^32". The reason to do this is because, even though there is an integer division instruction div/idiv in the instruction set, it's typically very slow, several times slower than multiplication.

    The second part calculates the remainder by multiplying the result of division by 10 (in an indirect way, via shifts and adds; presumably the compiler thinks that it will be faster that way) and then subtracting that from the original number.

提交回复
热议问题