yasar
yasar

Reputation: 13728

Divide Signed Integer By 2 compiles to complex assembly output, not just a shift

Consider this C function;

int triangle(int width, int height)
{
    return (width * height) / 2;
}

When compiled with gcc (gcc -m32 -g -c test.c) produces following assembly (objdump -d -M intel -S test.o).

test.o:     file format elf32-i386


Disassembly of section .text:

00000000 <triangle>:

int triangle(int width, int height)
{
   0:   55                      push   ebp
   1:   89 e5                   mov    ebp,esp
    return (width * height) / 2;
   3:   8b 45 08                mov    eax,DWORD PTR [ebp+0x8]
   6:   0f af 45 0c             imul   eax,DWORD PTR [ebp+0xc]
   a:   89 c2                   mov    edx,eax
   c:   c1 ea 1f                shr    edx,0x1f
   f:   01 d0                   add    eax,edx
  11:   d1 f8                   sar    eax,1
  13:   5d                      pop    ebp
  14:   c3                      ret    

I already know that shifting an integer n bit to right divides it by 2^n. However, according to above output, signed integers seems to be treated differently (which, of course, make sense). If I am reading assembly output correctly, sign bit of the integer added to itself before it is shifted.

What is the purpose of adding sign bit of the integer to itself before right shifting?

Upvotes: 0

Views: 583

Answers (1)

BeeOnRope
BeeOnRope

Reputation: 64875

It is to get the correct "rounding towards zero" result for negative numbers. Division by shifting rounds towards negative infinity, so negative numbers will have a different result compared to the expected result of the C division operator.

An example is -1: shifting right by 1 gives -1 still, but the C operator / 2 gives 0.

So the extra code is a correction for this effect. If you don't need that, use unsigned or an explicit shift (but the second option is less portable).

Upvotes: 2

Related Questions