Method: BitMagic::BitField#write_bits

Defined in:
lib/bit_magic/bit_field.rb

#write_bits(bit_values = {}) ⇒ Integer

Write to the specified bits, changing the internal @value to the new value

Examples:

Write new bit withs with their corresponding values

bit_field = BitField.new
bit_field.write_bits(0 => true) #=> 1
bit_field.write_bits(1 => true, 4 => true) #=> 19 # 10011
bit_field.write_bits(0 => false, 4 => false) #=> 2 # 10

Parameters:

  • bit_values (Hash) (defaults to: {})

    a hash with the key being a bit index and value being the value (must be 1, 0, true or false)

Returns:

  • (Integer)

    the value after writing the new bits their new values



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/bit_magic/bit_field.rb', line 76

def write_bits(bit_values = {})
  bit_values.each_pair do |index, val|
    
    if !index.is_a?(Integer)
      raise InputError.new("BitField#write can only access bits by their index, #{index.inspect} is not a valid index")
    end
    
    if index < 0
      raise InputError.new("BitField#write can not write to negative indices")
    end
    
    if !(val === true) and !(val === false) and !(val === 1) and !(val === 0)
      raise InputError.new("BitField#write must have a boolean value, #{val.inspect} is not a boolean")
    end
    
    if val === true or val === 1
      @value |= (1 << index)
    else
      @value &= ~(1 << index)
    end
  
  end
  
  @value
end