Class: BitField
- Inherits:
-
Object
- Object
- BitField
- 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
-
#get(bit_idx) ⇒ Boolean
(also: #retrieve)
Retrieves the bit at the specified index.
-
#initialize ⇒ BitField
constructor
Constructs a new BitField.
-
#set(bit_idx) ⇒ Object
(also: #toggle)
Toggles the bit at the specified index.
Constructor Details
#initialize ⇒ BitField
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
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.
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 |