Mail Archives: djgpp/2000/03/03/19:22:20
That "Campbell, Rolf [SKY:1U32:EXCH]" <moscoop AT americasm01 DOT nt DOT com>
really knows where his towel is. On Thu, 02 Mar 2000 09:45:01 -0500,
he wrote:
>Chris Mears wrote:
>
>> That Trancelucid <trancelucid AT videotron DOT ca> really knows where his
>> towel is. On Thu, 02 Mar 2000 06:07:49 -0500, he wrote:
>>
>> >DAVID JACOBS wrote:
>> >>
>> >> What is the fastest way to check wether an int/long is odd or even?
>> >> I've checked my C/C++ manual, but I didn't find anything....
>> >
>> >Just mask the bit 0..
>> >
>> >if(i & 0x01) {
>> > printf("odd");
>> >}
>> >else {
>> > printf("even");
>> >}
>>
>> I don't know how well this will work with signed integers.
>
>It should work fine with signed integers....
>-1 = 0xFFFFFFFF (lowest bit set)
>-2 = 0xFFFFFFFE (lowest bit not set)
Might not work on other machines, though. (I honestly don't know,
I've never used a machine that wasn't 2's-complement)
>
>> I believe
>> the fastest[*] way is:
>>
>> #define EVEN(x) (((x) % 2) == 0)
>> #define ODD(x) (((x) % 2) != 0)
>
>A literal "%" requires a divide (which is slow). I suspect that with
>optimizations on it would be reduced to (x&1) anyways.
Why do the optimisations yourself? We have compilers to do things
like that. We should write code that's easy to read, change and
maintain and if it's still not fast enough, that's when we optimise
things.
--
Chris Mears
chris_mears AT softhome DOT net
ICQ: 36697123
- Raw text -