K
Klaas Vantournhout
Hi,
I have a question, which is just out of interest.
What is the fastest way to do an odd/even check with c++ and if needed
assembler.
Assume n is an unsigned integer like type (unsigned int, unsigned long
int), what is the fastest?
using the modulo operator
a) if (n%2 == 0) then even
b) if (n%2 == 1) then odd
c) if (n%2 != 1) then even
d) if (n%2 != 0) then odd
using the bit shift operator
e) if ((n >> 1) << 1 == n) then even
f) if ((n >> 1) << 1 != n) then odd
g) if (((n >> 1) << 1) - n == 0) then even
h) if (n - ((n >> 1) << 1) == 1) then odd
They always told me that checking against '0' is the best for "speed",
if you can call it speed here ;-), thus this rules out b and c for sure.
But what would it be? I think bitshifts are faster then modulo
calculations. Is this right?
The most fast would be checking the last bit in the binary array. Is it
1, then it is odd else it is even. Can you do bitchecks in a number
with c++?
I can think of a rule, assume you want to check bit 5, you can do
n & (1<<5) == (1<<5)
but this is for sure not faster then just reading the bit. Because you
do 64 operations with the & and 64 operations with the checking, which
is much more then 2 operations.
So I was just wondering.
Anybody an idea?
Thanks
Klaas
I have a question, which is just out of interest.
What is the fastest way to do an odd/even check with c++ and if needed
assembler.
Assume n is an unsigned integer like type (unsigned int, unsigned long
int), what is the fastest?
using the modulo operator
a) if (n%2 == 0) then even
b) if (n%2 == 1) then odd
c) if (n%2 != 1) then even
d) if (n%2 != 0) then odd
using the bit shift operator
e) if ((n >> 1) << 1 == n) then even
f) if ((n >> 1) << 1 != n) then odd
g) if (((n >> 1) << 1) - n == 0) then even
h) if (n - ((n >> 1) << 1) == 1) then odd
They always told me that checking against '0' is the best for "speed",
if you can call it speed here ;-), thus this rules out b and c for sure.
But what would it be? I think bitshifts are faster then modulo
calculations. Is this right?
The most fast would be checking the last bit in the binary array. Is it
1, then it is odd else it is even. Can you do bitchecks in a number
with c++?
I can think of a rule, assume you want to check bit 5, you can do
n & (1<<5) == (1<<5)
but this is for sure not faster then just reading the bit. Because you
do 64 operations with the & and 64 operations with the checking, which
is much more then 2 operations.
So I was just wondering.
Anybody an idea?
Thanks
Klaas