Class: BitField

Inherits:
Object
  • Object
show all
Defined in:
lib/bitfield.rb

Overview

A BitField is a small 8-bit object whose bits can be modified and retrieved. It serves as a (hopefully) reliable, memory efficient, constrained collection of flags.

Instance Method Summary collapse

Constructor Details

#initializeBitField

Constructs a new BitField



8
9
10
# File 'lib/bitfield.rb', line 8

def initialize
  @source = [0xff].pack('C')
end

Instance Method Details

#get(bit_idx) ⇒ Boolean Also known as: retrieve

Retrieves the bit at the specified index

Parameters:

  • bit_idx (Integer)

    the bit index

Returns:

  • (Boolean)

    bit value



26
27
28
# File 'lib/bitfield.rb', line 26

def get(bit_idx)
  to_bin_rep(to_int).reverse[bit_idx] == '0'
end

#set(bit_idx) ⇒ Object Also known as: toggle

Toggles the bit at the specified index.

Parameters:

  • bit_idx (Integer)

    the bit index



14
15
16
17
18
19
# File 'lib/bitfield.rb', line 14

def set(bit_idx)
  current = to_bin_str
  current[bit_idx] = current[bit_idx] == '0' ? '1' : '0'
  @source = [from_bin_rep(current.reverse)].pack('C')
  nil
end