This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Compute the division via shift instruction

I write the code as following to evaluate the expression n = n / 2

asrs r0, r0, #1

But, I found the GCC will translate the expression n = n / 2 into the following instruction

lsrs r1, r0, #31                                                                             

adds r0, r1, r0

asrs r0, r0, #1

Why does it need to add the sign bit?

Parents
  • Hello Chi-wai,

    it is because to compensate shift error in the negative integer case.

    For example, we think of -3 (i.e. 0xFFFFFFFD).

    If is it right shifted by 1, the result is 0xFFFFFFFE  (-2). Although we expect it as 0xFFFFFFFF (-1).

    Therefore by adding the sign bit to 0xFFFFFFFD, making 0xFFFFFFFE.

    By right shifting 0xFFFFFFFE by 1, resulting to 0xFFFFFFFF. It will match with our expectation.

    Best regards,

    Yasuhiko Koumoto.

Reply
  • Hello Chi-wai,

    it is because to compensate shift error in the negative integer case.

    For example, we think of -3 (i.e. 0xFFFFFFFD).

    If is it right shifted by 1, the result is 0xFFFFFFFE  (-2). Although we expect it as 0xFFFFFFFF (-1).

    Therefore by adding the sign bit to 0xFFFFFFFD, making 0xFFFFFFFE.

    By right shifting 0xFFFFFFFE by 1, resulting to 0xFFFFFFFF. It will match with our expectation.

    Best regards,

    Yasuhiko Koumoto.

Children
No data