Basic knowledge: 7/2 and 6/2 are in the computer. 3. Division in C language is not equivalent to division in mathematical sense.
Division in C language. This method is set to zero.
-__________ 0 ___________ +
Only when the divisor is a constant. The compiler will be optimized.
1. Division with positive divisor and power of 2
#include main( argc, * iNum =, iNum / , iNum /
The disassembly of the corresponding Release version is as follows:
+ ; ASCII ; ASCII
Isn't it strange that there is no division command. Read the CPU manual. The number of instruction cycles for division. Scary. It is worth considering the cpu model. Read the manual.
So. The compiler tries its best. To avoid division. Improve efficiency.
mov esi, dword ptr [esp+
Cdq extends the symbol bit to edx and then performs addition. We know. If the divisor is positive, its value remains unchanged. Divide by the power of 2. It is equal to the right shift of sar.
If the divisor is negative. The sar is shifted to the right. It is equivalent to rounded down. The C language is set to zero. So. You must try to perform the following operations. This satisfies the objective-to-zero integer of the C language.
So the formula comes. A is the dividend number, and n is the power of 2. (a + 2 ^ n-1)/2 ^ n
For iNum/2, that is equal to (iNum + 2-1)/2. Constant folding. Equal to (iNum + 1)/2. Divide by 2 to shift one digit to the right of sar.
Then the optimization is perfectly solved by dividing by 2 and there is no difference. The total cycle of the command. It is much less than div commands.
The iNum/4 is deduced according to the formula. (INum + 2 ^ 2-1)/2 ^ 2. Constant folding. Equal to (iNum + 3)/4. Divide by 4 to remove two places to the right of sar.
The compilation code is as follows.
Recommended books: C ++ disassembly and reverse analysis technology secrets.
China's first institution engaged in software reverse engineer training. Strongly recommended http://www.51asm.com!