Example:
Input any number: 22
Output: Highest order set bit in 22 is 4.
Required knowledge:
Basic C programming, Bitwise operator, Loop, If elseHighest order set bit
Highest position of a set bit from left to right in a number is said to be highest order set bit of that number. Highest order set bit of any negative integers is 31 (using 32 bit signed integer) since the highest order set bit of any negative number is generally its most significant bit (MSB).Logic:
Highest order set bit can be found easily if you know how to check if a bit is set or not. What you need to do is simply iterate over each bits of the number and check whether the current bit is set or not.Program:
/** * C program to find highest order set bit in a number */ #include <stdio.h> #define INT_SIZE sizeof(int) * 8 //Integer size in bits int main() { int num, order=0, i; //Reads a number from user printf("Enter any number: "); scanf("%d", &num); //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; } printf("Highest 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
Highest order set bit in 22 is 4
Highest order set bit in 22 is 4
Happy coding ;)
You may also like
- Bitwise operator programming exercises index.
- C program to get lowest 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 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.