0

How can I check if a variable (an int) is even (that is, not odd) in C without using "%" operator? I am running on linux platform.

Thank you.

mah
  • 39,056
  • 9
  • 76
  • 93
michael
  • 106,540
  • 116
  • 246
  • 346

3 Answers3

9
if (!(v & 1))

should be true for even numbers

Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113
  • I google it and see people using 'return (((a>>1)<<1) == a)'. Why this solution is suggested, what case does it cover that (V&1) does not? – michael Mar 14 '14 at 23:00
  • might be different for negative numbers on systems with certain representations of negative integers? – Jason Goemaat Mar 15 '14 at 17:52
3

Try bitwise AND with 0x01 to check if last binary digit is 0 or 1.

In case of 0 it's even, whereas in case of 1 it's odd.

chrk
  • 4,037
  • 2
  • 39
  • 47
0

Just for providing an alternative answer, not that this is any better... You could use the following comparison to check whether an int is even (divisible by 2), where asd shall be an int:

asd == asd / 2 * 2;     //returns 1 (true) if asd is even
Utkan Gezer
  • 3,009
  • 2
  • 16
  • 29