Skip to content

Commit 0e1bfe6

Browse files
committed
Merge branch 'pr-13'
2 parents ab9512e + 7b281a1 commit 0e1bfe6

File tree

3 files changed

+9
-7
lines changed

3 files changed

+9
-7
lines changed

lib/bitarray-array.rb

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ class BitArray
33
attr_reader :field
44
include Enumerable
55

6-
VERSION = "1.2.0"
6+
VERSION = "1.3.0"
77
ELEMENT_WIDTH = 32
88

99
def initialize(size, field = nil)
@@ -43,8 +43,9 @@ def each_byte
4343
end
4444

4545
# Returns the total number of bits that are set
46-
# (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
46+
# Use Brian Kernighan's way, see
47+
# https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
4748
def total_set
48-
@field.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
49+
@field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }
4950
end
5051
end

lib/bitarray.rb

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ class BitArray
33
attr_reader :field
44
include Enumerable
55

6-
VERSION = "1.2.0"
6+
VERSION = "1.3.0"
77

88
def initialize(size, field = nil, reverse_byte: true)
99
@size = size
@@ -47,9 +47,10 @@ def each_byte
4747
end
4848

4949
# Returns the total number of bits that are set
50-
# (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
50+
# Use Brian Kernighan's way, see
51+
# https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
5152
def total_set
52-
@field.bytes.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
53+
@field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }
5354
end
5455

5556
def byte_position(position)

test/test_bitarray.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
require "minitest/autorun"
2-
require "bitarray"
2+
require_relative "../lib/bitarray"
33

44
class TestBitArray < Minitest::Test
55
def setup

0 commit comments

Comments
 (0)