Module: BinData::BitField
- Defined in:
- lib/bindata/bits.rb
Overview
Defines a number of classes that contain a bit based integer. The integer is defined by endian and number of bits.
Class Method Summary collapse
- .create_clamp_code(nbits) ⇒ Object
- .define_class(nbits, endian) ⇒ Object
- .define_methods(bit_class, nbits, endian) ⇒ Object
Class Method Details
.create_clamp_code(nbits) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/bindata/bits.rb', line 51 def create_clamp_code(nbits) min = 0 max = (1 << nbits) - 1 clamp = "(val < #{min}) ? #{min} : (val > #{max}) ? #{max} : val" if nbits == 1 # allow single bits to be used as booleans clamp = "(val == true) ? 1 : (not val) ? 0 : #{clamp}" end "val = #{clamp}" end |
.define_class(nbits, endian) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/bindata/bits.rb', line 9 def define_class(nbits, endian) name = "Bit#{nbits}" name << "le" if endian == :little unless BinData.const_defined?(name) BinData.module_eval <<-END class #{name} < BinData::BasePrimitive BitField.define_methods(self, #{nbits}, :#{endian}) end END end BinData.const_get(name) end |
.define_methods(bit_class, nbits, endian) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/bindata/bits.rb', line 23 def define_methods(bit_class, nbits, endian) bit_class.module_eval <<-END def assign(val) #{create_clamp_code(nbits)} super(val) end def do_write(io) io.writebits(_value, #{nbits}, :#{endian}) end def do_num_bytes #{nbits / 8.0} end #--------------- private def read_and_return_value(io) io.readbits(#{nbits}, :#{endian}) end def sensible_default 0 end END end |