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 number: 11
Output: Least Significant Bit of 11 is set (1).

Required knowledge:

Basic C programming, Bitwise operator, If else

Logic:

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.
Checking Least Significant Bit (LSB) in C
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:

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

#include <stdio.h>

int main()
{
    int num;

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

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

    return 0;
} 


Output
Enter any number: 11
Least Significant Bit (LSB) of 11 is set (1).

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment