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.

Class Method Summary collapse

Class Method Details

.create_float_methods(float_class, precision, endian) ⇒ Object

:nodoc: all



8
9
10
11
12
13
14
# File 'lib/bindata/float.rb', line 8

def self.create_float_methods(float_class, precision, endian)
  read = create_read_code(precision, endian)
  to_binary_s = create_to_binary_s_code(precision, endian)
  nbytes = (precision == :single) ? 4 : 8

  define_methods(float_class, nbytes, read, to_binary_s)
end

.create_read_code(precision, endian) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/bindata/float.rb', line 16

def self.create_read_code(precision, endian)
  if precision == :single
    unpack = (endian == :little) ? 'e' : 'g'
    nbytes = 4
  else # double_precision
    unpack = (endian == :little) ? 'E' : 'G'
    nbytes = 8
  end

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

.create_to_binary_s_code(precision, endian) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/bindata/float.rb', line 28

def self.create_to_binary_s_code(precision, endian)
  if precision == :single
    pack = (endian == :little) ? 'e' : 'g'
  else # double_precision
    pack = (endian == :little) ? 'E' : 'G'
  end

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

.define_methods(float_class, nbytes, read, to_binary_s) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/bindata/float.rb', line 38

def self.define_methods(float_class, nbytes, read, to_binary_s)
  float_class.module_eval <<-END
    def _do_num_bytes(ignored)
      #{nbytes}
    end

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

    def sensible_default
      0.0
    end

    def value_to_binary_string(val)
      #{to_binary_s}
    end

    def read_and_return_value(io)
      #{read}
    end
  END
end