
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
8
|
Chapter 1: Numbers and Enumerations
Discussion
Every odd number always has its least-significant bit set to 1. Therefore, by checking
whether this bit is equal to
1, you can tell whether it is an odd number. Conversely,
testing the least-significant bit to see whether it is
0 can tell you whether it is an even
number.
To test whether a value is even, you AND the value in question with
1 and then
determine whether the result is equal to zero. If it is, you know that the value is an
even number; otherwise, the value is odd. This operation is part of the
IsEven
method.
On the other hand, you can determine whether a value is odd by ANDing the value
with
1, similar to how the even test operates, and then determine whether the result
is
1. If so, you know that the value is an odd number; otherwise, the value is even.
This operation is part of the
IsOdd method.
Note that you do not have to implement both the
IsEven and IsOdd methods in your
application, although implementing both methods might improve the readability of
your code. You can implement one in terms of the other. For example, here is an
implementation of
IsOdd in terms of IsEven:
public static bool IsOdd(int intValue)
{
return (!IsEven(intValue));
}
The methods presented here accept only 32-bit integer values. To allow this method
to accept ...