C Program to Find the Highest Bit Set for any Given Integer

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:

  1. The program starts by including the necessary header file stdio.h for input/output operations.
  2. The findHighestBitSet function is defined. It takes an integer num as input and returns the position of the highest bit set.
  3. Inside the findHighestBitSet function, an integer variable position is declared and initialized to 0. This variable will keep track of the bit position.
  4. The program enters a while loop that continues until num becomes 0. This loop is responsible for right-shifting num by 1 bit in each iteration.
  5. Inside the loop, num is right-shifted by 1 bit using the >>= operator. This operation effectively divides num by 2.
  6. The position variable is incremented by 1 in each iteration to keep track of the number of right shifts performed.
  7. Once num becomes 0, the loop exits, and the value of position represents the position of the highest bit set in the original number.
  8. The main function is defined. It is the entry point of the program.
  9. Inside main, an integer variable num is declared to store the user input.
  10. The user is prompted to enter an integer using the printf function.
  11. The scanf function is used to read the user input and store it in the num variable.
  12. The findHighestBitSet function is called with the num variable as an argument. The returned value, representing the position of the highest bit set, is stored in the highestBitPosition variable.
  13. Finally, the program outputs the highest bit set position using the printf function.

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

C Program to Find the Highest Bit Set for any Given Integer