aspose file tools*
The moose likes Programming Diversions and the fly likes [easy]Most Significant Bit Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "[easy]Most Significant Bit" Watch "[easy]Most Significant Bit" New topic
Author

[easy]Most Significant Bit

Jason Menard
Sheriff

Joined: Nov 09, 2000
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

Joined: Jun 13, 2000
Posts: 3340
How's this for quick and dirty.

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

I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
Jason Menard
Sheriff

Joined: Nov 09, 2000
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

Joined: Jun 13, 2000
Posts: 3340
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

Joined: Nov 09, 2000
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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: [easy]Most Significant Bit