Module: BinData::FloatingPoint

Defined in:
lib/bindata/float.rb

Overview

Defines a number of classes that contain a floating point number. The float is defined by precision and endian.

Constant Summary collapse

PRECISION =
{
  single: 4,
  double: 8,
}
PACK_CODE =
{
  [:single, :little] => 'e',
  [:single, :big]    => 'g',
  [:double, :little] => 'E',
  [:double, :big]    => 'G',
}

Class Method Summary collapse

Class Method Details

.create_num_bytes_code(precision) ⇒ Object



44
45
46
# File 'lib/bindata/float.rb', line 44

def create_num_bytes_code(precision)
  PRECISION[precision]
end

.create_read_code(precision, endian) ⇒ Object



48
49
50
51
52
53
# File 'lib/bindata/float.rb', line 48

def create_read_code(precision, endian)
  nbytes = PRECISION[precision]
  unpack = PACK_CODE[[precision, endian]]

  "io.readbytes(#{nbytes}).unpack('#{unpack}').at(0)"
end

.create_to_binary_s_code(precision, endian) ⇒ Object



55
56
57
58
59
# File 'lib/bindata/float.rb', line 55

def create_to_binary_s_code(precision, endian)
  pack = PACK_CODE[[precision, endian]]

  "[val].pack('#{pack}')"
end

.define_methods(float_class, precision, endian) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/bindata/float.rb', line 21

def define_methods(float_class, precision, endian)
  float_class.module_eval <<-END
    def do_num_bytes
      #{create_num_bytes_code(precision)}
    end

    #---------------
    private

    def sensible_default
      0.0
    end

    def value_to_binary_string(val)
      #{create_to_binary_s_code(precision, endian)}
    end

    def read_and_return_value(io)
      #{create_read_code(precision, endian)}
    end
  END
end