Example:
Input number: 11
Output: Least Significant Bit of 11 is set (1).
Required knowledge:
Basic C programming, Bitwise operator, If elseLogic:
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.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).
Least Significant Bit (LSB) of 11 is set (1).
Happy coding ;)
You may also like
- Bitwise operator programming exercises index.
- C program to check Most Significant Bit (MSB) of a number is set or not.
- C program to get highest set bit of a number.
- C program to get lowest set bit of a number.
- C program to count trailing zeros in a binary number.
- C program to count leading zeros in a binary number.
- C program to flip bits of a binary number using bitwise operator.
- C program to total number of zeros and ones in a binary number.
- C program to convert decimal to binary number system using bitwise operator.
- C program to swap two numbers using bitwise operator.
- C program to check whether a number is even or odd using bitwise operator.