73

How do I check if an integer is even or odd using bitwise operators

Tim Post
  • 33,371
  • 15
  • 110
  • 174
brisk man
  • 749
  • 1
  • 6
  • 4

12 Answers12

151

Consider what being "even" and "odd" means in "bit" terms. Since binary integer data is stored with bits indicating multiples of 2, the lowest-order bit will correspond to 20, which is of course 1, while all of the other bits will correspond to multiples of 2 (21 = 2, 22 = 4, etc.). Gratuituous ASCII art:

NNNNNNNN
||||||||
|||||||+−− bit 0, value =   1 (20)
||||||+−−− bit 1, value =   2 (21)
|||||+−−−− bit 2, value =   4 (22)
||||+−−−−− bit 3, value =   8 (23)
|||+−−−−−− bit 4, value =  16 (24)
||+−−−−−−− bit 5, value =  32 (25)
|+−−−−−−−− bit 6, value =  64 (26)
+−−−−−−−−− bit 7 (highest order bit), value = 128 (27) for unsigned numbers,
                 value = -128 (-27) for signed numbers (2's complement)

I've only shown 8 bits there, but you get the idea.

So you can tell whether an integer is even or odd by looking only at the lowest-order bit: If it's set, the number is odd. If not, it's even. You don't care about the other bits because they all denote multiples of 2, and so they can't make the value odd.

The way you look at that bit is by using the AND operator of your language. In C and many other languages syntactically derived from B (yes, B), that operator is &. In BASICs, it's usually And. You take your integer, AND it with 1 (which is a number with only the lowest-order bit set), and if the result is not equal to 0, the bit was set.

I'm intentionally not actually giving the code here, not only because I don't know what language you're using, but because you marked the question "homework." :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
103

In C (and most C-like languages)

if (number & 1) {
  // It's odd 
}
Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
30
if (number & 1)
    number is odd
else // (number & 1) == 0
    number is even

For example, let's take integer 25, which is odd. In binary 25 is 00011001. Notice that the least significant bit b0 is 1.

00011001    
00000001   (00000001 is 1 in binary)
       &
--------
00000001
Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
T M
  • 3,195
  • 2
  • 31
  • 52
18

Just a footnote to Jim's answer.

In C#, unlike C, bitwise AND returns the resulting number, so you'd want to write:

if ((number & 1) == 1) {
   // It's odd
}
neontapir
  • 4,698
  • 3
  • 37
  • 52
  • 1
    I don't know C# (the question is tagged C anyway), but how does that make any difference? `number & 1` would return either 0 or 1. If in C# you write `if (8)` for example, doesn't the `8` evaluate to `true`? – Shahbaz Mar 26 '13 at 13:39
  • 1
    No, unlike C, an integer is not automatically cast to a Boolean in C#, so you'd get a compile error: "Constant value '8' cannot be converted to a 'bool'". Hence the extra syntax. I put this answer as a "footnote" so that people looking to use this in C# like I needed to would be able to use it. – neontapir Mar 26 '13 at 15:06
  • 6
    *"In C#, unlike C, bitwise AND returns the resulting number..."* Bitwise AND returns the resulting number in C, too. It'd be pretty useless if it didn't. It's the fact that `if` can operate on any integral type in C but not in C# that's different, not the result of the bitwise operator. – T.J. Crowder Feb 11 '14 at 10:08
  • My understanding is that in C, bitwise AND returns a Boolean result, whereas C# returns the value or 0. Take a look at the code samples in the OP and my answer to see the difference. – neontapir Feb 18 '14 at 21:46
  • 3
    The & operator, when used on integers, returns an integer by definition. `8 & 1` will give 0 as a result. However, in C, an if statement will cast 0 to false, and any non-zero number to true. – JimmyMcHoover Jun 17 '14 at 07:04
  • @neontapir In C, "bitwise AND" or `&` returns an integer result _at least_ as wide as type `int` - not the C boolean type `_Bool`. Detail: As part of the `if(x)`, if `x` compares equal to `0`, the `if()` branch is not taken. IAC, `if (number & 1)` and `if ((number & 1) == 1)` will generate the same code on a good compiler - there is no functional difference. – chux - Reinstate Monica Jun 21 '16 at 22:14
  • @chux, that's probably true. I wrote this answer because I came to this question 4 years ago to find the answer to C# and had to fiddle with it, so I shared my findings with others as a comment. I have no doubt what you say about the C compiler is true. – neontapir Jun 22 '16 at 04:34
10
if(x & 1)                               // '&' is a bit-wise AND operator
    printf("%d is ODD\n", x);
else
    printf("%d is EVEN\n", x);

Examples:

    For 9:

      9 ->        1 0 0 1
      1 ->     &  0 0 0 1
      -------------------
      result->    0 0 0 1

So 9 AND 1 gives us 1, as the right most bit of every odd number is 1.

     For 14:

       14 ->      1 1 1 0
       1  ->   &  0 0 0 1
       ------------------
       result->   0 0 0 0

So 14 AND 1 gives us 0, as the right most bit of every even number is 0.

Aditya Goel
  • 381
  • 3
  • 5
3

Also in Java you will have to use if((number&1)==1){//then odd}, because in Java and C# like languages the int is not casted to boolean. You'll have to use the relational operators to return a boolean value i.e true and false unlike C and C++ like languages which treats non-zero value as true.

TLama
  • 75,147
  • 17
  • 214
  • 392
rahulk9
  • 795
  • 3
  • 10
  • 20
2

You can do it simply using bitwise AND & operator.

if(num & 1)
{
    //I am odd number.
}

Read more over here - Checking even odd using bitwise operator in C

Pankaj Prakash
  • 2,300
  • 30
  • 31
2
Check Number is Even or Odd using XOR Operator 

Number = 11 
  1011  - 11 in Binary Format 
^ 0001  - 1 in Binary Format 
  ----
  1010  - 10 in Binary Format 

Number = 14 

  1110  - 14 in Binary Format 
^ 0001  - 1 in Binary Format 
  ----
  1111  - 15 in Binary Format 

AS It can observe XOR Of a number with 1, increments it by 1 if it is 
even, decrements it by 1 if it is odd. 

Code:

if((n^1) == (n+1))
    cout<<"even\n";
else
    cout<<"odd\n";
  • This answer does not answer the OP's question. Instead of having a convoluted answer that's hard to understand, use AND. That's what it's there for... cout << (n & 0x01) ? "odd\n" : "even\n"; – Daniel Rudy Jul 12 '21 at 20:39
1
#include <iostream>
#include <algorithm>
#include <vector>

void BitConvert(int num, std::vector<int> &array){
    while (num > 0){
        array.push_back(num % 2);
        num = num / 2;
    }
}

void CheckEven(int num){
    std::vector<int> array;
    BitConvert(num, array);
    if (array[0] == 0)
        std::cout << "Number is even";
    else
        std::cout << "Number is odd";
}

int main(){
    int num;
    std::cout << "Enter a number:";
    std::cin >> num;

    CheckEven(num);
    std::cout << std::endl;

    return 0;
}
Testing123
  • 363
  • 2
  • 12
1

In Java,

if((num & 1)==0){
//its an even num
}
//otherwise its an odd num
0

This is an old question, however the other answers have left this out.

In addition to using num & 1, you can also use num | 1 > num.

This works because if a number is odd, the resulting value will be the same since the original value num will have started with the ones bit set, however if the original value num was even, the ones bit won't have been set, so changing it to a 1 will make the new value greater by one.

qwerty
  • 810
  • 1
  • 9
  • 26
0

Approach 1: Short and no need for explicit comparison with 1

if (number & 1) {
  // number is odd
}
else {
  // number is even
}

Approach 2: Needs an extra bracket and explicit comparison with 0

if((num & 1) == 0){ // Note: Bracket is MUST around num & 1
  //  number is even
}
else {
  // number is odd
}

What would happen if I miss the bracket in the above code

if(num & 1 == 0) { } // wrong way of checking even or not!!

becomes

if(num & (1 == 0)) { } // == is higher precedence than &

https://en.cppreference.com/w/cpp/language/operator_precedence

SridharKritha
  • 8,481
  • 2
  • 52
  • 43