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

前端 未结 9 1462
迷失自我
迷失自我 2020-12-02 05:36

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

9条回答
  •  不知归路
    2020-12-02 06:17

    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.

提交回复
热议问题