Quantcast
Channel: User Alex Lop. - Stack Overflow
Viewing all articles
Browse latest Browse all 39

Answer by Alex Lop. for Why is /=2 different from >>=1 for signed integers, and compiles to different asm?

$
0
0

Dividing a negative integer by 2 is not the same as shifting it to the right by 1.For example

-7 / 2 = -3

With shifts:

11111001b >> 1 = 11111100b which is -4

Thus the compiler has to take care of the case when the integer is negative

What are cdq and sub doing? Are they necessary?

cdq performs the following EDX:EAX ← sign-extend of EAX.

Thus if the value in EAX is negative, EDX will get 0xFFFFFFFF (which is -1), otherwise it will be 0 (due to the sign extension of EAX).

sub eax, edx ; will either result in 'eax - 0' (if EAX is positive) or             ;                       'eax - (-1)' (if EAX is negative)

Which in case of the above example will normalize the -7 to -7 - (-1) = -6 and then -6 >> 1 = -3.


Viewing all articles
Browse latest Browse all 39

Trending Articles