I'm receiving a binary string which represents a group of 32-bit floats. It is reported from series of pairs of 16-bit MODBUS registers whereby th开发者_StackOverflow中文版e first register represents the lower bits and the second register represents the higher bits. I am able to, in a horrifically ugly manner, rearrange the registers then decode to a float. I'd like this to be quite a bit more attractive, but I'm failing at the task. Essentially, I'm unpacking the string to a hex string array, converting to string, slicing the high bits and putting them in front of the low bits, then converting it to integer base 16, packing it to a 32 bit integer, unpacking to a float, then selecting the first value in the array. If you'll excuse me, that last sentence makes me need to weep. Without further ado:
def read_dual_input_registers(addr, npairs)
@values = Array.new
result = <binary-string-returned-here>.unpack('H*').to_s
npairs.to_i.times do
register = result.slice!(4..7) + result.slice!(0..3)
@values.push([register.to_i(16)].pack('L').unpack('F')[0])
end
@values
end
Does this work?
t = <binary-string-returned-here>
result = (t[2..3] + t[0..1]).unpack('F')[0]
精彩评论