# [easy]Most Significant Bit

Jason Menard
Sheriff
Posts: 6450
This is rather trivial, but I'm curious to see whether or not anyone has any interesting approaches to this. I also thought I would throw in an actual programming diversion for a change as well.
The problem: give an input long integer (let's assume positive, but I'd also be interested in discussing the ramifications if any of considering negatives), return the position of the long's most significant bit (MSB).
For ease, I guess we can keep the count zero-based. Therefore, if we want the MSB of 7, the answer would be 2.

The leftmost one bit, the MSB, is in the 2^2 position, so the MSB of 7 is 2.

Carl Trusiak
Sheriff
Posts: 3341
How's this for quick and dirty.

[ August 26, 2003: Message edited by: Carl Trusiak ]

Jason Menard
Sheriff
Posts: 6450
Not too shabby.
For a more general solution, although probably not the best, here's what I came up with.

Carl Trusiak
Sheriff
Posts: 3341
Not bad, however for negitive numbers your routine returns 0 (OK, he did say may include negatives) However for large numbers such as Integer.MAX_VALUE it goes into an infinite loop.
Hows' this:

Now for 0 it returns -1 Where the String version returns 0 but, he did specify what that should return so, I guess both answers are correct
As the saying goes, no Specification, no Bug!

Jason Menard
Sheriff
Posts: 6450
Pretty good. I've got a special place in my heart for bit operations.
I guess there's something to be said for actually testing code, eh?