Class: BitArray

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/bitarray.rb,
lib/bitarray-array.rb

Constant Summary collapse

VERSION =
"1.2.0"
ELEMENT_WIDTH =
32

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size, field = nil) ⇒ BitArray

Returns a new instance of BitArray.



8
9
10
11
12
# File 'lib/bitarray.rb', line 8

def initialize(size, field = nil, reverse_byte: true)
  @size = size
  @field = field || "\0" * (size / 8 + 1)
  @reverse_byte = reverse_byte
end

Instance Attribute Details

#fieldObject (readonly)

Returns the value of attribute field.



3
4
5
# File 'lib/bitarray.rb', line 3

def field
  @field
end

#sizeObject (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)



24
25
26
# File 'lib/bitarray.rb', line 24

def [](position)
  (@field.getbyte(position >> 3) & (1 << (byte_position(position) % 8))) > 0 ? 1 : 0
end

#[]=(position, value) ⇒ Object

Set a bit (1/0)



15
16
17
18
19
20
21
# File 'lib/bitarray.rb', line 15

def []=(position, value)
  if value == 1
    @field.setbyte(position >> 3, @field.getbyte(position >> 3) | (1 << (byte_position(position) % 8)))
  else
    @field.setbyte(position >> 3, @field.getbyte(position >> 3) & ~(1 << (byte_position(position) % 8)))
  end
end

#byte_position(position) ⇒ Object



48
49
50
# File 'lib/bitarray.rb', line 48

def byte_position(position)
  @reverse_byte ? position : 7 - position
end

#each(&block) ⇒ Object

Iterate over each bit



29
30
31
# File 'lib/bitarray.rb', line 29

def each(&block)
  @size.times { |position| yield self[position] }
end

#to_sObject

Returns the field as a string like “0101010100111100,” etc.



34
35
36
37
38
39
40
# File 'lib/bitarray.rb', line 34

def to_s
  if @reverse_byte
    @field.bytes.collect { |ea| ("%08b" % ea).reverse }.join[0, @size]
  else
    @field.bytes.collect { |ea| ("%08b" % ea) }.join[0, @size]
  end
end

#total_setObject

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)



44
45
46
# File 'lib/bitarray.rb', line 44

def total_set
  @field.bytes.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
end