On Sat, 11 Aug 2012 09:48:15 -0400, David <d...@dav1d.de> wrote:

-1 % 16 = -1

Shouldn't that be 15? It seems like the sign is ignored for the modulo.

Is this a bug or intended behaviour? The Python implementation returns here, as expected, 15.

In case you are still looking for an expression which mods always positive (even for non-powers of 2)

(a % b + b) % b

Obviously, b must be positive.

The direct translation of this to assembly isn't the most efficient way.

Technically, in assembly we could check for the sign bit, and only add b again (without doing the second mod) if the value was negative. But I'm not sure you can write an expression that causes that, maybe:

a % b < 0 ? a % b + b : a % b

Certainly not as appealing. To get a direct translation from the above assembly, it would be something like:

typeof(a) x;

auto expr = (x = a % b) < 0 ? x + b : x

-Steve

Reply via email to