delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/03/02/12:34:47

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: <l5jsbs87qgu43hr16el30msklmmao5j2h1@4ax.com>
References: <38BE28A9 DOT CD476C62 AT student DOT kuleuven DOT ac DOT be> <38BE4B85 DOT 1F5A0778 AT videotron DOT ca>
X-Newsreader: Forte Agent 1.7/32.534
MIME-Version: 1.0
Lines: 60
Date: Thu, 02 Mar 2000 22:19:26 +1100
NNTP-Posting-Host: 139.134.199.97
X-Trace: newsfeeds.bigpond.com 951995582 139.134.199.97 (Thu, 02 Mar 2000 22:13:02 EST)
NNTP-Posting-Date: Thu, 02 Mar 2000 22:13:02 EST
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

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.  I believe
the fastest[*] way is:

#define EVEN(x) (((x) % 2) == 0)
#define ODD(x) (((x) % 2) != 0)

I'm not sure how this would work with negative numbers.  You could
stay out of trouble by using the macros with abs():

if (EVEN(abs(x)))
  /* number is even... */

But this has its own problem.  Consder:

void foo(void)
{
  int x;
  int y;

  x = INT_MIN;
  y = abs(INT_MIN);
}

This will break many implementations, since the smallest negative
value that is able to be represented by int will have a greater
magnitude that the largest positive value representable by int.

Anyway, to answer the question, try the macros at the top of my post.
;-)

[*] for specific values of "fastest".


-- 
Chris Mears

chris_mears AT softhome DOT net
ICQ: 36697123

Herman: How many men do you have?
Bart:   None.
Herman: You'll need more.
---- ``Bart the General''

- Raw text -


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