C program to check Least Significant Bit (LSB) of a number is set or not

Write a C program to input any number from user and check whether the Least Significant Bit (LSB) of the given number is set (1) or not (0). How to check whether the least significant bit of a number is set or unset using bitwise operator in C programming. C program to get the status of least significant bit of a number.

Example

Input

Input number: 11

Output

Least Significant Bit of 11 is set (1).

Required knowledge

Basic C programming, Bitwise operator, If else

Logic to check Least Significant Bit (LSB) of a number

To check the status of Least Significant Bit (LSB) of any number we will use bitwise AND & operator. Even for checking the current status of any bit we use bitwise AND operator. We know that bitwise AND operator evaluates each bit of the result to 1 if the corresponding bits of both operands are 1. Now to check the LSB of any number we are going to perform bitwise AND operation with the number and 1. The bitwise AND operation number & 1 will evaluate to 1 if and only if the LSB of number is 1 otherwise will evaluate to 0.

Even odd using bitwise operator

In the above image you can see that 12 & 1 evaluates to 0 since LSB of 12 is 0. And the operation 15 & 1 evaluates to 1 since LSB of 15 is 1.

Program to check Least Significant Bit (LSB) of a number

/**
 * C program to check Least Significant Bit (LSB) of a number using bitwise operator
 */

#include <stdio.h>

int main()
{
    int num;

    // Input a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    //If (num & 1) evaluates to 1
    if(num & 1)
        printf("LSB of %d is set (1).", num);
    else
        printf("LSB of %d is unset (0).", num);

    return 0;
}

Output

Enter any number: 11
LSB of 11 is set (1).

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>