bit-level operations – check integer is even or odd

In this short article I will exaplain how to use bit-level operations to verify that integer is even or odd. It’s very useful and fast verification.

Examples below have been compiled and tested using gnu-gcc.

$/> gcc example.c -o example

CHECK EVEN

To verify that integer is even we need to check first bit is not set.

#include <stdint.h>
#include <assert.h>

int
main(void)
{
    uint8_t n = 10; // 0b00001010
    assert((n & 1) == 0);
    return (0);
}

CHECK ODD

To verify that integer is odd we need to check first bit is set.

#include <stdint.h>
#include <assert.h>

int
main(void)
{
    uint8_t n = 11; // 0b00001011
    assert((n & 1) > 0);
    return (0);
}

USEFUL MACROS

#include <stdint.h>
#include <stdbool.h>
#include <assert.h>

#define IS_EVEN(n) (((n) & 0x01) == 0)
#define IS_ODD(n)  (((n) & 0x01) > 0)

int
main(void)
{

    assert(IS_EVEN(1) == false);
    assert(IS_EVEN(2) == true);
    assert(IS_ODD(1) == true);
    assert(IS_ODD(2) == false);

    return (0);
}

Leave a Comment