Skip to content

Commit

Permalink
Merge pull request #52 from peelman/add-little-endian-float
Browse files Browse the repository at this point in the history
Add extension method to support unpacking 32-bit Int using little-endian
  • Loading branch information
fmluizao committed Mar 15, 2017
2 parents c9125f6 + c948a68 commit 84b05c2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
6 changes: 6 additions & 0 deletions lib/rmodbus/ext.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ def to_32f
self.each_slice(2).map { |(lsb, msb)| [msb, lsb].pack('n*').unpack('g')[0] }
end

# Given an array of 16bit Fixnum, we turn it into 32bit Int in little-endian order, halving the size
def to_32f_le
raise "Array requires an even number of elements to pack to 32bits: was #{self.size}" unless self.size.even?
self.each_slice(2).map { |(lsb, msb)| [lsb, msb].pack('n*').unpack('g')[0] }
end

# Given an array of 32bit Floats, we turn it into an array of 16bit Fixnums, doubling the size
def from_32f
self.pack('g*').unpack('n*').each_slice(2).map { |arr| arr.reverse }.flatten
Expand Down
7 changes: 6 additions & 1 deletion spec/ext_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,15 @@
[20342, 17344, 20342, 17344].to_32i.size.should == 2
end

it "should turn an array into 32b floats" do
it "should turn an array into 32b floats big endian" do
[20342, 17344].to_32f[0].should be_within(0.1).of(384.620788574219)
[20342, 17344, 20342, 17344].to_32f.size.should == 2
end

it "should turn a an array into 32b floats (little endian)" do
[17344, 20342].to_32f_le[0].should be_within(0.1).of(384.620788574219)
[17344, 20342, 17344, 20342].to_32f_le.size.should == 2
end

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

0 comments on commit 84b05c2

Please sign in to comment.