Skip to content

Commit

Permalink
Added spec and implementation of #to_ieee754f which is used by Eastro…
Browse files Browse the repository at this point in the history
…n SDM630 meter.
  • Loading branch information
mariuspod committed Sep 30, 2015
1 parent 2843776 commit 7f185ee
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/rmodbus/ext.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,21 @@ def from_32i
self.pack('N*').unpack('n*').each_slice(2).map { |arr| arr.reverse }.flatten
end

# As seen here: https://en.wikipedia.org/wiki/IEEE_floating_point
def to_ieee754f
binary = self.map{|e| e.to_s(2).rjust(16, '0')}.inject{|bin, e| bin + e}
negative_multiplier = binary[0] == "1" ? -1.0 : 1.0
exponent = binary[1..8].to_i(2) - 127
mantissa = "1." + binary[9..-1]
number = negative_multiplier * 10 ** exponent * mantissa.to_f
splitted = number.to_s.split(".")
before_comma = splitted[0].to_i(2)
after_comma = splitted[1].split(//).each_with_index.map do |bit, i|
bit.to_i * 2 ** (-i-1)
end.inject{|memo, e| memo + e}
(before_comma + after_comma).to_f
end

def pack_to_word
word = 0
s = ""
Expand Down
5 changes: 5 additions & 0 deletions spec/ext_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
[20342, 17344, 20342, 17344].to_32f.size.should == 2
end

it "should turn an array of bytes in IEEE754 format into the correct 32b float" do
[17264,32768].to_ieee754f.should be_within(0.1).of(240.5)
[16029, 2081].to_ieee754f.should be_within(0.1).of(0.3)
end

it "should turn an array from 32b ints into 16b ints, big endian" do
[1136676726].from_32i.should == [20342, 17344]
[1136676726, 1136676725].from_32i.should == [20342, 17344, 20341, 17344]
Expand Down

0 comments on commit 7f185ee

Please sign in to comment.