Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method · added in Ruby 4.1

Integer#bit_count

bit_count → integer

Returns the number of set bits (bits equal to 1) in the binary representation of self, also known as the population count or Hamming weight.

Example
0.bit_count            # => 0
1.bit_count            # => 1
7.bit_count            # => 3
0b10101.bit_count      # => 3
255.bit_count          # => 8
(2**1000).bit_count    # => 1
(2**1000-1).bit_count  # => 1000

Raises an exception if self is negative.

Example
(-1).bit_count # Raises ArgumentError

Ruby version changes

  1. 4.1
    • Integer#bit_count is added. It returns the number of 1 bits in the binary representation of a non-negative integer (its population count). [Feature #20163]