class BitArray

Overview

BitArray is an array data structure that compactly stores bits.

Bits externally represented as Bools are stored internally as UInt32s. The total number of bits stored is set at creation and is immutable.

BitArray includes all the methods in Enumerable.

Example

require "bit_array"
ba = BitArray.new(12) # => "BitArray[000000000000]"
ba[2]                 # => false
0.upto(5) { |i| a[i*2] = true }
ba                    # => "BitArray[101010101010]"
ba[2]                 # => true

Superclass hierarchy

Object
Reference
BitArray

Included Modules

Enumerable(Bool)

Defined in:

Class Method Summary

Instance Method Summary

Class Method Detail

def self.new(length, initial = false : Bool)

Create a new BitArray of #length bits.

initial optionally sets the starting value, true or false, for all bits in the array.


Instance Method Detail

def [](index)

Returns the bit at the given index. Negative indices can be used to start counting from the end of the array. Raises IndexError if trying to access a bit outside the array's range.

ba = BitArray.new(5)
ba[3] # => false

def []=(index, value : Bool)

Sets the bit at the given index. Negative indices can be used to start counting from the end of the array. Raises IndexError if trying to access a bit outside the array's range.

ba = BitArray.new(5)
ba[3] = true

def each(&block)

def invert

Inverts all bits in the array. Falses become true and vice versa.

ba = BitArray.new(5)
ba[2] = true; ba[3] = true
ba # => BitArray[00110]
ba.invert
ba # => BitArray[11001]

def length

The number of bits the BitArray stores


def to_s(io : IO)

def toggle(index)

Toggles the bit at the given index. A false bit becomes a true bit, and vice versa. Negative indices can be used to start counting from the end of the array. Raises IndexError if trying to access a bit outside the array's range.

ba = BitArray.new(5)
ba[3] # => false
ba.toggle(3)
ba[3] # => false