From: "tenderlovemaking (Aaron Patterson) via ruby-core" Date: 2026-07-07T17:11:43+00:00 Subject: [ruby-core:125956] [Ruby Feature#20163] Introduce #bit_count method on Integer Issue #20163 has been updated by tenderlovemaking (Aaron Patterson). I found a few more examples "in the wild": * [MOBI parser/generator](https://github.com/slonopotamus/dyck/blob/b031a8b396e55067d78c6ff85ff4f0f3bb8bc46c/lib/dyck/util.rb#L13-L17) * [TON blockchain SDK](https://github.com/nerzh/ton-sdk-ruby/blob/42d482c180426b6b565c3e1fe31bfe2d2dbef8e1/lib/ton-sdk-ruby/boc/mask.rb#L42-L46) * [ARM64 encoder](https://github.com/tenderlove/aarch64/blob/27d2ed1088f8babda48006dc8bf4e057cd12f6b3/lib/aarch64/instructions.rb#L23-L30) * [Another IP address library](https://github.com/izawa/cidr/blob/73e7af76138b46f32e37a8e7b57ad966493ecd49/lib/cidr/aggregator.rb#L49-L55) ---------------------------------------- Feature #20163: Introduce #bit_count method on Integer https://bugs.ruby-lang.org/issues/20163#change-117929 * Author: garrison (Garrison Jensen) * Status: Open ---------------------------------------- This feature request is to implement a method called #bit_count on Integer that returns the number of ones in the binary representation of the absolute value of the integer. ``` n = 19 n.bit_count #=> 3 (-n).bit_count #=> 3 ``` This is often useful when you use an integer as a bitmask and want to count how many bits are set. This would be equivalent to ``` n.to_s(2).count("1") ``` However, this can be outperformed by ``` def bit_count(n) count = 0 while n > 0 n &= n - 1 # Flip the least significant 1 bit to 0 count += 1 end count end ``` I think this would be a useful addition because it would fit alongside the other bit-related methods defined on integer: `#bit_length,` `#allbits?`, `#anybits?`, `#nobits?`. Also, when working with bitmasks, a minor upgrade to performance often results in a significant improvement. Similar methods from other languages: https://docs.python.org/3/library/stdtypes.html#int.bit_count https://doc.rust-lang.org/std/primitive.i32.html#method.count_ones -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/