Find the highest order bit in C

Question :

Find the highest order bit in C,

Answer :

what I’m after is something I can feed a number into and it will return the highest order bit. I’m sure there’s a simple way. Below is an example output (left is the input)

1 -> 1  2 -> 2  3 -> 2  4 -> 4  5 -> 4  6 -> 4  7 -> 4  8 -> 8  9 -> 8  ...  63 -> 32

,

From Hacker’s Delight:

int hibit(unsigned int n) {      n |= (n >>  1);      n |= (n >>  2);      n |= (n >>  4);      n |= (n >>  8);      n |= (n >> 16);      return n - (n >> 1);  }  

This version is for 32-bit ints, but the logic can be extended for 64-bits or higher.

Read More  Replicating load related crashes in non-production environments

That’s the answer Find the highest order bit in C, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you