how to get the thighest bit position in big integers?

MRAB google at mrabarnett.plus.com
Wed Oct 8 13:26:57 EDT 2008


On Oct 8, 9:56 am, Mark Dickinson <dicki... at gmail.com> wrote:
> On Oct 7, 5:19 pm, mmgar... at gmx.de wrote:
>
> > but I want to make clear that I think that (0).numbits()==-1
> > is the natural solution. At least for all square-and-multiply-like
> > algorithms needed in [...]
>
> Can you clarify this?  Why is -1 the natural solution? I
> can see a case for 0, for -infinity (whatever that means),
> or for raising an exception, but I can't see why -1 would
> be at all useful or natural.
>
[snip]
Compare it with, say, str.find, which returns the position if found
(>=0) or -1 if not found.

int.numbits should return the position of the highest set bit (>=0) or
-1 if none found.

On the other hand, if you compare it wirh str.index then int.numbits
should raise ValueError if none found.

Actually, the name "numbits" suggests that it returns the number of
bits, so (1).numbits() should return 1 and (0).numbits() should return
0. If it's called "highbit" then it suggests that it returns the
position of the highest (set) bit, so (1).highbit() should return 0
and (0).highbit() should return -1 (or raise an exception).



More information about the Python-list mailing list