Example:
Input any number: 22
Output first set bit: 1
Required knowledge:
Basic C programming, Bitwise operator, If else, LoopLowest order set bit
Lowest order or first set bit of any number is the first bit set starting from left to right. Lowest order set bit of any odd number is 0 since the first bit of any odd number is always set.Logic:
As I explained in how to find highest order set bit finding lowest order set bit is also very easy if you know how to check if a bit is set or not. What you need to do is to iterate over each bit of the number and stop when you find the first set bit.Program:
/** * C program to find lowest order set bit in a number */ #include <stdio.h> #define INT_SIZE sizeof(int) * 8 //Integer size in bits int main() { int num, order, i; //Reads a number from user printf("Enter any number: "); scanf("%d", &num); //Initially sets the order to max size of integer order = INT_SIZE - 1; //Loops over each bit of the integer for(i=0; i<INT_SIZE; i++) { //If the current bit is set if((num>>i) & 1) { order = i; break; //No need to check further } } printf("Lowest order set bit in %d is %d", num, order); return 0; }
Note: Here I have assumed that bit ordering starts from 0.
Output
Enter any number: 22
Lowest order set bit in 22 is 1
Lowest order set bit in 22 is 1
Happy coding ;)
You may also like
- Bitwise operator programming exercises index.
- C program to get highest set bit of a number.
- C program to check Least Significant Bit (LSB) of a number is set or not.
- C program to check Most Significant Bit (MSB) of a number is set or not.
- C program to get nth bit of a number.
- C program to set nth bit of a number.
- C program to clear nth bit of a number.
- C program to toggle nth bit of a number.
- C program to flip bits of a binary number using bitwise operator.
- 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.