Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the highest order bit in C [duplicate]

Tags:

c

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
like image 463
Harley Holcombe Avatar asked Sep 09 '08 23:09

Harley Holcombe


People also ask

How do you find most significant bit C?

To get MSB of the number, move first bit of 1 to highest order. Left shift 1 bits - 1 times and store result in some variable say msb = 1 << (bits - 1) . If bitwise AND operation num & msb evaluate to 1 then MSB of num is set otherwise not.

How do I find MSB?

A simple solution is to one by one divide n by 2 until it becomes 0 and increment a count while doing this. This count actually represents the position of MSB.

What is the MSB?

The term "money services business" includes any person doing business, whether or not on a regular basis or as an organized business concern, in one or more of the following capacities: (1) Currency dealer or exchanger. (2) Check casher. (3) Issuer of traveler's checks, money orders or stored value.


2 Answers

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.

like image 53
erickson Avatar answered Oct 04 '22 05:10

erickson


fls bottoms out to a hardware instruction on many architectures. I suspect this is probably the simplest, fastest way of doing it.

1<<(fls(input)-1) 
like image 45
Fabian Avatar answered Oct 04 '22 06:10

Fabian