Method: BitMagic::Bits#read

Defined in:
lib/bit_magic/bits.rb

#read(name, field = nil) ⇒ Integer Also known as: []

Read a field or bit from its bit index or name

Examples:

Read bit values

# The struct is just an example, normally you would define a new class
Example = Struct.new('Example', :flags)
exo = Example.new(9)
bits = Bits.new(exo, {:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4})
bits.read(:is_odd) #=> 1
bits.read(:amount) #=> 4
bits.read(:is_cool) #=> 0
bits.read(:amount, BitField.new(78)) #=> 7
# Bonus: aliased as []
bits[:is_odd] #=> 1

Parameters:

  • name (Symbol, Integer)

    either the name of the bit (a key in field_list) or a integer bit position

  • field (BitField optional) (defaults to: nil)

    a specific BitField to read from. default: return value of #field

Returns:

  • (Integer)

    a value of the bit (0 or 1) or bits (number from 0 to (2**bit_length) - 1) or nil if the field name is not in the list



219
220
221
222
223
224
225
226
227
# File 'lib/bit_magic/bits.rb', line 219

def read(name, field = nil)
  field ||= self.field
  
  if name.is_a?(Integer)
    field.read_field(name)
  elsif bits = @field_list[name]
    field.read_field(bits)
  end
end