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 any number: 22
Output: Highest order set bit in 22 is 4.

Required knowledge:

Basic C programming, Bitwise operator, Loop, If else

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 of a number

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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment