Class: BitArray

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/bitarray/bit_array.rb

Constant Summary collapse

VERSION =
"1.3.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size, field = nil, reverse_byte: true) ⇒ BitArray

Returns a new instance of BitArray.



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

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.



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

def field
  @field
end

#reverse_byteObject (readonly)

Returns the value of attribute reverse_byte.



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

def reverse_byte
  @reverse_byte
end

#sizeObject (readonly)

Returns the value of attribute size.



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

def size
  @size
end

Instance Method Details

#[](position) ⇒ Object

Read a bit (1/0)



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

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

#[]=(position, value) ⇒ Object

Set a bit (1/0)



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

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

#eachObject

Iterate over each bit



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

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

#each_byteObject

Iterates over each byte



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

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.



34
35
36
37
38
39
40
# File 'lib/bitarray/bit_array.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 Use Brian Kernighan’s way, see graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan



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

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