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
numeric.c
View on GitHub ↗
VALUE
rb_int_bit_count(VALUE num)
{
if (FIXNUM_P(num)) {
return rb_fix_bit_count(num);
}
else if (RB_BIGNUM_TYPE_P(num)) {
return rb_big_bit_count(num);
}
UNREACHABLE_RETURN(Qnil);
}
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
-
4.1
-
Integer#bit_countis added. It returns the number of1bits in the binary representation of a non-negative integer (its population count). [Feature #20163]
-