Class: BitArray
- Inherits:
-
Object
- Object
- BitArray
- Includes:
- Enumerable
- Defined in:
- lib/bitarray.rb,
lib/bitarray-array.rb
Constant Summary collapse
- VERSION =
"1.0.0"
- ELEMENT_WIDTH =
32
Instance Attribute Summary collapse
-
#field ⇒ Object
readonly
Returns the value of attribute field.
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
-
#[](position) ⇒ Object
Read a bit (1/0).
-
#[]=(position, value) ⇒ Object
Set a bit (1/0).
-
#each(&block) ⇒ Object
Iterate over each bit.
-
#initialize(size, field = nil) ⇒ BitArray
constructor
A new instance of BitArray.
-
#to_s ⇒ Object
Returns the field as a string like “0101010100111100,” etc.
-
#total_set ⇒ Object
Returns the total number of bits that are set (The technique used here is about 6 times faster than using each or inject direct on the bitfield).
Constructor Details
#initialize(size, field = nil) ⇒ BitArray
Returns a new instance of BitArray.
8 9 10 11 |
# File 'lib/bitarray.rb', line 8 def initialize(size, field = nil) @size = size @field = "\0" * (size / 8 + 1) end |
Instance Attribute Details
#field ⇒ Object (readonly)
Returns the value of attribute field.
3 4 5 |
# File 'lib/bitarray.rb', line 3 def field @field end |
#size ⇒ Object (readonly)
Returns the value of attribute size.
2 3 4 |
# File 'lib/bitarray.rb', line 2 def size @size end |
Instance Method Details
#[](position) ⇒ Object
Read a bit (1/0)
23 24 25 |
# File 'lib/bitarray.rb', line 23 def [](position) (@field.getbyte(position >> 3) & (1 << (position % 8))) > 0 ? 1 : 0 end |
#[]=(position, value) ⇒ Object
Set a bit (1/0)
14 15 16 17 18 19 20 |
# File 'lib/bitarray.rb', line 14 def []=(position, value) if value == 1 @field.setbyte(position >> 3, @field.getbyte(position >> 3) | (1 << (position % 8))) else @field.setbyte(position >> 3, @field.getbyte(position >> 3) ^ (1 << (position % 8))) end end |
#each(&block) ⇒ Object
Iterate over each bit
28 29 30 |
# File 'lib/bitarray.rb', line 28 def each(&block) @size.times { |position| yield self[position] } end |
#to_s ⇒ Object
Returns the field as a string like “0101010100111100,” etc.
33 34 35 |
# File 'lib/bitarray.rb', line 33 def to_s @field.bytes.collect{|ea| ("%08b" % ea).reverse}.join[0, @size] end |
#total_set ⇒ Object
Returns the total number of bits that are set (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
39 40 41 |
# File 'lib/bitarray.rb', line 39 def total_set @field.bytes.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a } end |