
Arithmetic Shifting Considered Harmful (1976) [pdf] - tjalfi
https://dspace.mit.edu/bitstream/handle/1721.1/6090/AIM-378.pdf?sequence=2&isAllowed=y
======
saagarjha
In general, trying to perform operations which truncate on negative numbers is
fraught with peril, because everyone seems to do it differently and you need
to look it up. Another one that tends to bite people is the modulus operator
where either operand is negative: programming languages tend to differ on what
the result should be. For example:

    
    
      $ echo "print(-7 % 3)" | python3
      2
      $ echo "print(-7 % -3)" | python3
      -1
      $ echo "System.out.println(-7 % 3)" | jshell -
      -1
      $ echo "System.out.println(-7 % -3)" | jshell -
      -1

~~~
0xff00ffee
Wikipedia has a huge list of mod implementations:

[https://en.wikipedia.org/wiki/Modulo_operation](https://en.wikipedia.org/wiki/Modulo_operation)

------
CalChris
x86-64 clang 10.0.0 -O2 uses _asr_

[https://godbolt.org/z/2PAP5c](https://godbolt.org/z/2PAP5c)

~~~
freshbob
x >> 2 resulting in SAR is quite logical. I'm more concerned about

x / 2 resulting in the off-by-one error mentioned in the paper, if x is
LLONG_MIN. LLONG_MIN / 2 = 0 in with their optimization.

[https://godbolt.org/z/EtyNsR](https://godbolt.org/z/EtyNsR)

~~~
Thorrez
> x / 2 resulting in the off-by-one error mentioned in the paper, if x is
> LLONG_MIN. LLONG_MIN / 2 = 0 in with their optimization.

Are you saying clang is leading to an off-by-one error? The code seems to
behave correctly to me.

------
a1369209993
> Dividing -1 by 2 gives a quotient of 0 and a remainder of -1 (See the DIVMOD
> routine if you want to check this out). But shifting -1 right by one bit
> gives -1. [1]

Yes, this is because asr/and rounds toward negative infinity (as it should),
while your DIVMOD (also round toward -inf) routine incorrectly[0] implements
QUOREM (round toward zero).

0: Well, you could say that it's rather the _name_ that is incorrect, since I
gather it's _intended_ to implement quo/rem rather than div/mod.

~~~
BlackFingolfin
There is no standard that says quo/rem or div/mod should mean one or the
other. And in fact there are more than just two choices for how to implement
these. See e.g.
[https://en.wikipedia.org/wiki/Modulo_operation](https://en.wikipedia.org/wiki/Modulo_operation)

------
dang
Url changed from
[https://apps.dtic.mil/dtic/tr/fulltext/u2/a031883.pdf](https://apps.dtic.mil/dtic/tr/fulltext/u2/a031883.pdf)
to one that seems to load much faster.

