delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/03/03/19:22:20

From: Chris Mears <chris_mears AT softhome DOT net>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: odd or even?
Organization: only if absoultely necessary
Message-ID: <tsg0csclt7k7q6suq7vdcq2gua5aacq8kh@4ax.com>
References: <38BE28A9 DOT CD476C62 AT student DOT kuleuven DOT ac DOT be> <38BE4B85 DOT 1F5A0778 AT videotron DOT ca> <l5jsbs87qgu43hr16el30msklmmao5j2h1 AT 4ax DOT com> <38BE7E6D DOT 6FE78AC9 AT americasm01 DOT nt DOT com>
X-Newsreader: Forte Agent 1.7/32.534
MIME-Version: 1.0
Lines: 53
Date: Sat, 04 Mar 2000 10:02:06 +1100
NNTP-Posting-Host: 139.134.82.41
X-Trace: newsfeeds.bigpond.com 952124137 139.134.82.41 (Sat, 04 Mar 2000 09:55:37 EST)
NNTP-Posting-Date: Sat, 04 Mar 2000 09:55:37 EST
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019