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
io_buffer.c
View on GitHub ↗
static VALUE
io_buffer_bit_count(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 0, 2);
size_t offset, length;
struct rb_io_buffer_view *buffer = io_buffer_extract_offset_length(self, argc, argv, &offset, &length);
io_buffer_validate_range(buffer, offset, length);
const void *base;
size_t size;
io_buffer_get_bytes_for_reading(buffer, &base, &size);
if (length == 0) return SIZET2NUM(0);
RUBY_ASSERT(base != NULL);
size_t count = memory_bit_count((const unsigned char *)base + offset, length);
return SIZET2NUM(count);
}
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