Mail Archives: djgpp/1998/02/16/03:41:55
Erik Max Francis wrote:
>
> Demandred wrote:
>
> > Hmmm... random() returns a random (duh) integer that can be pretty
> > huge (0 to MAXINT, IIRC), so I'd guess that the & 7 (bitwise AND with
> > 111b) acts like a % 8 (modulus 8)(??). Why, I don't know... maybe
> > bitwise AND is faster than mod?
>
> x%n is the same as x&(n - 1), when n is a power of 2.
>
> Bitwise operations are much, much faster than integer division operators
> (/, %).
However, since our gcc compiler is smart enough to see that modulus
operations with a divisor which is a power of 2, can be implemented as
bitwise operations, it may be a better choice to choose for ::operator%
rather than ::operator&, especially when the divisor is not a integer
literal, but a symbolic constant.
e.g. the libc.a "rand ()" function, returns and integer between 0 and
RAND_MAX, by doing something like "sd & RAND_MAX". This works well as
long as no one decides to alter RAND_MAX to be different from a constant
like 2^n-1, otherwise it will fail.
On the other hand "sd % (RAND_MAX+1)" will always produce the expected
result, and the compiler will produce equally efficient code if
possible.
--
\ Vik /-_-_-_-_-_-_/
\___/ Heyndrickx /
\ /-_-_-_-_-_-_/
- Raw text -