Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

[easy]Most Significant Bit

 
Jason Menard
Sheriff
Posts: 6450
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How's this for quick and dirty.

[ August 26, 2003: Message edited by: Carl Trusiak ]
 
Jason Menard
Sheriff
Posts: 6450
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic