Class: BitArray

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

Constant Summary collapse

VERSION =
"1.3.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



56
57
58
# File 'lib/bitarray.rb', line 56

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

#eachObject

Iterate over each bit



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

def each
  return to_enum(:each) unless block_given?
  @size.times { |position| yield self[position] }
end

#each_byteObject

Iterate over each byte



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

def each_byte
  return to_enum(:each_byte) unless block_given?
  @field.bytes.each{ |byte| yield byte }
end

#to_sObject

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



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

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 Use Brian Kernighan’s way, see graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan



52
53
54
# File 'lib/bitarray.rb', line 52

def total_set
  @field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }
end