This C program calculates and displays the position of the highest bit set (most significant bit) for a given integer. The highest bit set is the leftmost (most significant) bit that is turned on (1) in the binary representation of the integer.
Problem Statement
Write a C program that finds the position of the highest bit set (most significant bit) for a given integer.
C Program to Find the Highest Bit Set for any Given Integer
#include <stdio.h>
int findHighestBitSet(int num) {
int position = 0;
while (num > 0) {
num = num >> 1; // Right shift by 1 bit
position++;
}
return position;
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
int highestBit = findHighestBitSet(num);
printf("The highest bit set in %d is at position %d.\n", num, highestBit);
return 0;
}
How it works
Let’s go through how the program works step by step:
- The program starts by including the necessary header file
stdio.hfor input/output operations. - The
findHighestBitSetfunction is defined. It takes an integernumas input and returns the position of the highest bit set. - Inside the
findHighestBitSetfunction, an integer variablepositionis declared and initialized to 0. This variable will keep track of the bit position. - The program enters a
whileloop that continues untilnumbecomes 0. This loop is responsible for right-shiftingnumby 1 bit in each iteration. - Inside the loop,
numis right-shifted by 1 bit using the>>=operator. This operation effectively dividesnumby 2. - The
positionvariable is incremented by 1 in each iteration to keep track of the number of right shifts performed. - Once
numbecomes 0, the loop exits, and the value ofpositionrepresents the position of the highest bit set in the original number. - The
mainfunction is defined. It is the entry point of the program. - Inside
main, an integer variablenumis declared to store the user input. - The user is prompted to enter an integer using the
printffunction. - The
scanffunction is used to read the user input and store it in thenumvariable. - The
findHighestBitSetfunction is called with thenumvariable as an argument. The returned value, representing the position of the highest bit set, is stored in thehighestBitPositionvariable. - Finally, the program outputs the highest bit set position using the
printffunction.
That’s how the program works! It takes an input integer, finds the position of the highest bit set using a right-shift operation, and displays the result to the user.
Input/Output
