# Difference between mod and bitwise And operator

• 06-18-2012
Swoorup
Difference between mod and bitwise And operator
Hi,
Can someone give me the differences between & and % ?
I have the following algorithm which limits a random variable to 255 only.

int nRand = rand();
nRand %= 255;

Now , doesn't the last statement have similar effect when replacing it with this.
nRand &= 255;
?
• 06-18-2012
laserlight
Quote:

Originally Posted by Swoorup
Can someone give me the differences between & and % ?

What do those operations do?

Quote:

Originally Posted by Swoorup
I have the following algorithm which limits a random variable to 255 only.

int nRand = rand();
nRand %= 255;

Actually, that would set 254 to be the upper limit, but it presumably is a typo and you wanted to write 256.

Quote:

Originally Posted by Swoorup
Now , doesn't the last statement have similar effect when replacing it with this.
nRand &= 255;

Yes (once the typo is corrected), but that is just a coincidence.
• 06-18-2012
Swoorup
So, you mean, they are the same
if I change nRand %= 255 to
nRand %= 256?
• 06-18-2012
laserlight
Quote:

Originally Posted by Swoorup
So, you mean, they are the same
if I change nRand %= 255 to
nRand %= 256?

No, they are not the same. They will just have the same effect of limiting the range of the value.
• 06-18-2012
Swoorup
I see, thank you.
Which one would be the most effective for picking random though?
• 06-18-2012
Salem
Changing x %= 256 into x &= 256 is an optimisation many compilers can do for themselves.

If you're going to optimise anything, then focus on the whole algorithm (like bubble sort vs. quicksort) where your skills can make a real difference.
Micro optimisations at the single operator level won't do much for you.
• 06-18-2012
Swoorup
Hmm, thank you
Is the opmization of the compiler like this though? when x %= 256 then x &= 255 not x &= 256 :p

I am learning about the lower-level details of C++ and finding out the relation between assembly and C++ via debugging them. So, minor things like this happened to boggle my mind :P
• 06-18-2012
laserlight
Quote:

Originally Posted by Swoorup
Is the opmization of the compiler like this though? when x %= 256 then x &= 255

Maybe. It depends on whether the compiler can prove that the result will always be the same. For example, -1 % 256 == -1, but -1 % 255 == 255, assuming two's complement. Now, we know for sure that rand() returns a non-negative integer, but the compiler may or may not be able to determine this, or if it can, it might not have done so. Then, there's the issue of proving that for every non-negative integer i in the range of int, (i % 256) == (i & 255).
• 06-18-2012
R41D3N