Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Int#bit_length #8924

Merged
merged 8 commits into from
Mar 22, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion spec/std/int_spec.cr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require "spec"
require "./spec_helper"
RX14 marked this conversation as resolved.
Show resolved Hide resolved
{% unless flag?(:win32) %}
require "big"
{% end %}
Expand Down Expand Up @@ -777,4 +777,15 @@ describe "Int" do
65.unsafe_chr.should eq('A')
(0x10ffff + 1).unsafe_chr.ord.should eq(0x10ffff + 1)
end

it "#bit_length" do
RX14 marked this conversation as resolved.
Show resolved Hide resolved
0.bit_length.should eq(0)
0b1.bit_length.should eq(1)
0b1001.bit_length.should eq(4)
0b1001001_i64.bit_length.should eq(7)
-1.bit_length.should eq(0)
-10.bit_length.should eq(4)

BigInt.new("1234567890123456789012345678901234567890").bit_length.should eq(130)
end
end
35 changes: 35 additions & 0 deletions src/int.cr
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,41 @@ struct Int
(self & mask) == mask
end

# Returns the number of bits of this int value.
#
# “The number of bits” means that the bit position of the highest bit
# which is different to the sign bit.
# (The bit position of the bit 2**n is n+1.)
# If there is no such bit (zero or minus one), zero is returned.
#
# I.e. This method returns `ceil(log2(self < 0 ? -self : self + 1))`.
#
# ```
# 0.bit_length # => 0
# 1.bit_length # => 1
# 2.bit_length # => 2
# 3.bit_length # => 2
# 4.bit_length # => 3
# 5.bit_length # => 3
#
# # The above is the same as
# 0b0.bit_length # => 0
# 0b1.bit_length # => 1
# 0b10.bit_length # => 2
# 0b11.bit_length # => 2
# 0b100.bit_length # => 3
# 0b101.bit_length # => 3
# ```
def bit_length : self
x = self < 0 ? ~self : self

if x.is_a?(Int::Primitive)
self.class.new(sizeof(self) * 8 - x.leading_zeros_count)
else
self.class.new(Math.log2(x).to_i + 1)
end
end

# Returns the greatest common divisor of `self` and `other`. Signed
# integers may raise overflow if either has value equal to `MIN` of
# its type.
Expand Down