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
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With