Mail Archives: djgpp/2000/03/02/12:34:47
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 -