Project

General

Profile

Actions

Feature #8700

closed

Integer#bitsize (actually Fixnum#bitsize and Bignum#bitsize)

Added by akr (Akira Tanaka) almost 12 years ago. Updated almost 12 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:56247]

Description

How about adding Integer#bitsize (actually Fixnum#bitsize and Bignum#bitsize)?

Integer#bitsize returns the position of the most significant bit in the absolute value.
(The position of the least significant bit is 1.)
It returns 0 if no bit set (i.e. the value 0).

Mathematically, n.bitsize is ceil(log2(abs(n)+1)).

Sometimes we want to know the size of a integer.

There are several software which has similar feature.

I think there are two concerns for this issue.

  • method name
  • behavior for zero and negative number

I named the method as bitsize, mainly because
there is Fixnum#size and Bignum#size.
However I'm open for other names such as:

  • bitlength
  • numbits
  • ilog2
  • maxbit
    Some names may suggest different behavior, though.

The behavior for zero and negative number is not trivial.

Python adopts ceil(log2(abs(n)+1)) but
Java and Mathematica adopts ceil(log2(n < 0 ? -n : n+1)).
The difference is absolute number v.s. 2's complement number.

Some people may prefer ilog2, which name suggests ilog2(0) raise an error.

I choose ceil(log2(abs(n)+1)). (i.e. absolute number, same as Python).
I think absolute number is easier to understand than 2's complement for many people.

I attached the implementation as bitsize.patch.
The patch implements both Bignum#bitsize and Fixnum#bitsize in bignum.c.
It is because Fixnum#bitsize uses bitsize macro and it is defined in bignum.c.
Maybe, the macro should be moved to internal.h and the implementation of
Fixnum#bitsize should be moved to numeric.c.

Any comments?


Files

bitsize.patch (4.88 KB) bitsize.patch akr (Akira Tanaka), 07/28/2013 10:56 PM
bitlength.patch (4.94 KB) bitlength.patch akr (Akira Tanaka), 08/01/2013 08:47 PM
bit_length.patch (4.59 KB) bit_length.patch akr (Akira Tanaka), 08/05/2013 09:48 PM
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0