C Program to check LSB status of number
C Program to check least significant bit (LSB) of a number
Write a C program to take a number as input from user and check whether the least significant bit (LSB) of that number is set (if LSB is 1) to or not (if LSB is 0). How to check status of LSB and of a number using bitwise AND (&) operator and what is the logic are given below.
Remember: Least significant bit (LSB) is also known as right most bit which is the bit position in binary sequence.
Before writing any program you just imagine about output screen first. Like what input to be given, and output to be displayed. Let's have a look at the below example.
- INPUT
- Enter first number: 10
- Enter second number: 20
OUTPUT
Sum of 10 and 20 = 30
Required knowledge for this exercise
Logic to check LSB of a number using bitwise AND & operator:
As we know that the bitwise AND (&) operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
To check LSB of a number we need to perform bitwise AND operation. The bitwise AND operation number & 1
will evaluate to 1 if LSB of number is set i.e. 1 otherwise evaluates to 0. See the below example. As you can see in above image 12 & 1
evaluate to 0. Since, LSB of 12 is 0. Whereas, 15 & 1
evaluate to 1 since LSB of 15 is 1.
Program to to check least significant bit LSB of a number:
-
#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
- * Note: If (num & 1) is equivalent to If (num & 1 == 1)
- */
if(num & 1)
printf("LSB of %d is set (1).", num);
else
printf("LSB of %d is not set i.e (0).", num);
return 0;
}
Output:
- Enter any number: 12
- LSB of 12 is not set i.e (0)
As you can see in above image,12 & 1
evaluate to 0. Since, LSB of 12 is 0. similarly you can check LSB of any number.
Help others by sharing this page.
Ahmad Irshad
Author & Editor
I love blogging, teaching, learning computer science and sharing it to others. I've written and develped this site so that students may learn computer science related tutorials eaisly. MCA / MCITP
Wednesday, July 15, 2020
C
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.