Method: CTypes::Helpers#bitfield

Defined in:
lib/ctypes/helpers.rb

#bitfield(type = nil, bits = nil) { ... } ⇒ Object

create a Bitfield type

Examples:

dynamically sized

t = bitfield(a: 1, b: 2, c: 3)
t.pack({c: 0b111})    # => "\x38" (0b00111000)

fixed size to pad to 16 bits.

t = bitfield(uint16, a: 1, b: 2, c: 3)
t.pack({c: 0b111})    # => "\x38\x00" (0b00111000_00000000)

Parameters:

  • type (Type) (defaults to: nil)

    type to use for packed representation

  • bits (Hash) (defaults to: nil)

    map of name to bit count

Yields:



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/ctypes/helpers.rb', line 170

def bitfield(type = nil, bits = nil, &block)
  if bits.nil? && !block
    bits = type
    type = nil
  end

  Class.new(Bitfield) do
    if bits
      layout do
        bytes(type.size) if type
        bits.each do |name, size|
          unsigned name, size
        end
      end
    else
      layout(&block)
    end
  end
end