Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: rmodbus/rmodbus
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: main
Choose a base ref
...
head repository: mariuspod/rmodbus
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
Can’t automatically merge. Don’t worry, you can still create the pull request.
  • 1 commit
  • 2 files changed
  • 1 contributor

Commits on Sep 30, 2015

  1. Copy the full SHA
    7f185ee View commit details
Showing with 20 additions and 0 deletions.
  1. +15 −0 lib/rmodbus/ext.rb
  2. +5 −0 spec/ext_spec.rb
15 changes: 15 additions & 0 deletions lib/rmodbus/ext.rb
Original file line number Diff line number Diff line change
@@ -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 = ""
5 changes: 5 additions & 0 deletions spec/ext_spec.rb
Original file line number Diff line number Diff line change
@@ -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]