Skip to content

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

instance method

IO::Buffer#bit_count

bit_count([offset, [length]]) → integer

Returns the number of set bits (1s) in the buffer, also known as the Hamming weight or population count. An optional offset and length can be provided to count bits in a subrange of the buffer.

Example
IO::Buffer.for("\xFF\x00\x0F").bit_count
# => 12

IO::Buffer.for("\xFF\x00\x0F").bit_count(1, 2)
# => 4