Topic : Signed vs. Unsigned Divide

Forum : ARM

Original Post
Post Information Post
February 8, 2010 - 10:36pm
Guest

If I divide an unsigned number by a signed number, why is a "udiv" instruction generated versus a "sdiv" instruction?

Example:

int32_t test_div (uint32_t num, int32_t den)
{
    int32_t result = num / den;
    return result;
}

This source generates the following assembly code:

0: fbb0 f0f1 udiv r0, r0, r1
4: 4770 bx lr
6: 46c0 nop (mov r8, r8)

I would expect that since the denominator is signed, and possibly negative, that an "sdiv" instruction would be generated instead of "udiv".

Can somebody please clue me in?

Thanks.

Replies
Post Information Post
+1
0
-1
February 8, 2010 - 10:53pm
Guest

Correction to the code:

int32_t test_div (int32_t num, uint32_t den)
{
    int32_t result = num / den;
    return result;
}

This matches my description better.

+1
0
-1
February 9, 2010 - 10:20am
Guest

Hi

As you probably noted this seems to be a type conversion due to the fact that you are using an operator with
arguments which are not from the same type.

There is a conversion choice which is done, and I do not know exactly the rule which is used.
You might either search for this rule or mya be someone in this forum know it.
Also you might change your code be sure to controle the kind of division you exepect.

Regards
Matloub

+1
0
-1
February 12, 2010 - 5:05pm
Guest

The general rule for the common binary operators is: when two operators signed/unsigned of the same size are used, both are converted to the 'unsigned' type, and the operation is performed as an unsigned operation.
When the type size are different, the 'bigger' type is choosen (whatever the 'signed' attribute).