Write a C program to input any number from user and find 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. Logic to get highest order set bit of a number in C programming.

**Example**

**Input**

Input any number: 22

**Output**

Highest order set bit in 22 is 4.

## Required knowledge

Bitwise operators, Data types, Variables and Expressions, Basic input/output, If else, For loop

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 (for 32 bit signed integer). Since, highest order set bit of any negative number is its Most Significant Bit (MSB).

## Logic to get highest order set bit of a number

Step by step descriptive logic to get highest order set bit of a number.

- Input number from user. Store it in some variable say,
`num`. - Find total bits required to store an integer in memory say,
`INT_SIZE = sizeof(int) * 8`

.Read more - How to find size of a data type using sizeof() operator.

- Run a loop from 0 to
`INT_SIZE`. The loop structure should look like`for(i=0; i<INT_SIZE; i++)`

. - Initialize a variable to store highest order, say
`order = -1;`

. - Inside the loop if
`i`bit is set then update^{th}`order`to`i`i.e.`order = i;`

.

## 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 = -1, i;
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
/* Iterate over each bit of integer */
for(i=0; i<INT_SIZE; i++)
{
/* If current bit is set */
if((num>>i) & 1)
order = i;
}
if (order != -1)
printf("Highest order set bit in %d is %d", num, order);
else
printf("0 has no set bits.");
return 0;
}
```

Output

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

Happy coding ðŸ˜‰

### Recommended posts

- 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 flip bits of a binary number using bitwise operator.
- C program to count trailing zeros in a binary number.
- C program to count leading zeros in a binary number.

<pre><code> ----Your Source Code---- </code></pre>