C program to get highest order set bit of a number

Write a C program to input any number from user and find the highest order set bit of given number using bitwise operator. How to find the highest order of the set bit of a given number using bitwise operator in C programming. Finding highest order set bit of any number in C programming.

Example

Input

Input any number: 22

Output

Highest order set bit in 22 is 4.

Required knowledge

Basic C programming, Bitwise operator, Loop, If else

Read more - Program to check if a bit is set or not

Highest 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).

Highest order set bit

Program to get highest order set bit of a number

/**
 * 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;

    // input a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    // Iterate 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: I have assumed that bit ordering starts from 0.

Output

Enter any number: 22
Highest order set bit in 22 is 4

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>