This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: Generating Modulo and Remainder Operations


Hi David,

The % operator is well-defined for unsigned integer numbers.  It is platform dependent when dealing with negatively signed integer numbers.

So if it is being used for negatively signed integer numbers, the results have platform dependent behavior.

> How would the conversion from signed to unsigned be done without a modulus function?

Rather depends on if you want Knuth modulus, or Euclidean modulus.  Both have their uses.

Given these meanings:
r := modulus result, aka, the remainder
n := numerator
d := denominator

And if the modulus result is expected to be between (Euclidean modulus):
0 <= r < d

Then you could use (off the top of my head... not actually tested):

int r = abs(n) % abs(d);
return ((n < 0) != (d < 0)) ? ((abs(d)-r)%abs(d)) : r;

There is probably a more efficient way of doing this same thing in Hacker's Delight by Henry S. Warren <http://www.amazon.com/dp/0201914654>.  I don't have it at my fingertips right now.

> I thought that was the whole point of having a modulus function.

Platform dependent behavior if either the lhs or rhs of the "lhs % rhs" is negative.

> I can always make a conversion like this [...snip...] But then I'm implementing a mod function myself.

Correct.

Or you can use the Standard C Library modf() function.

> Presumably this is the same in C++ which shares C's standard numerical library IIRC.

Correct.

Sincerely,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]