On most machines, the division of integers is slow and requires more than 30 clock cycles, divided by the power of 2, and can be implemented with shift operations.
Code on first
#include "stdio.h"
int main ()
{
int x=-128;
int Y=X/4;
printf ("y=%d", y);
}
Attach the assembly code again
PUSHL%EBP
. Cfi_def_cfa_offset 8
. Cfi_offset 5,-8
MOVL%esp,%EBP
. Cfi_def_cfa_register 5
Andl $-16,%esp
Subl $32,%esp
Movl $-128, (%ESP)
MOVL (%ESP),%eax
Leal 3 (%EAX),%edx
Testl%eax,%eax//This step is to test whether the value of the%EAX register is 0. And the flag-position ZF and SF are set to 0 or 1.
Cmovs%edx,%eax//cmovs, sign 1, that is, when the number of symbols, the implementation of the MOV instructions. This is a conditional directive.
SARL,%eax//Because, for example, as in C, the right shift is the arithmetic right shift. So it's equivalent to the C-expression (x<0? (x+ (1<<k)-1): x) >>k, because the C code is divided by 4, then the right shift is 2 bits.
Movl%eax, (%ESP)
MOVL (%ESP),%eax
MOVL%eax, 4 (%ESP)
MOVL $. LC0, (%ESP)
Call printf
The main purpose of writing this note is two points.
First, on most machines, the division instruction is slower than the integer multiplication instruction and requires 30 clock cycles. The shift requires only 1 or several clock cycles. This saves a lot of time.
So some compilers will compile the division into a right-shift instruction.
Second, when the arithmetic right shifts, it is to be discussed in categories. Because in most programming languages, the right shift is the arithmetic right shift.
x/(2^k), if X is positive, then right shift, high 0, this is no problem;
When x is negative, move right, high 1, then the resulting number is rounded down (for example, the resulting theoretical value is-2.1, then the result is--3)
So to add 1 in the low, that is, in the K position 1. Change to C language
(x<0?) (x+ (1<<k)-1): x) >>k,