I'm writing a CLI that interacts with an external USB device. The device's status is discovered by reading the Status registers, 24x 8 bits wide. The register values are read from a serial port and arrive as an array of Strings:
=> ["000", "000", "000", "000", "086", "003", "000", "000", "255", "255", ...]
The registers are in 2 formats, bit flags and BCD (I'm not sure of Correct terminology here). They can be mix also.
Bit flags
Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
---|---|---|---|---|---|---|---|
Error 10 | Error 11 | Error 12 | Error 13 | Error 14 | Error 15 | Error 16 | Error 17 |
A value of 34 (0b00100010) means 'Error 16' and 'Error 12' are present.
BCD
Bit 2 | Bit 1 | Bit 0 | result |
---|---|---|---|
0 | 0 | 0 | State A |
0 | 0 | 1 | State B |
0 | 1 | 0 | State C |
0 | 1 | 1 | State D |
1 | 1 | 1 | State E |
A value of 3 (0b00000011) means 'State D'
Is there an elegant Ruby way (or conventions) for storing and looking up this type of String data?
CodePudding user response:
Although I don't quite understand what's the relation between the 24*8 Status registers and Bit flags and BCD, but I think it's just about the number base conversion.
You can use to_s
if you want to change the number base from 2 to 36.
5.to_s(2)
# => '101'
255.to_s(2)
# => '11111111'
36.to_s(36)
# => '10'
After you convert the number to binary, you can use rjust to supplement with the leading zeros.
5.to_s(2).rjust(8, '0')
# => '00000101'
Then you can use the index of the string to decide what is the status now.
For Bit flags, you can make a array of errors:
errors = ['Error 10', 'Error 11', 'Error 12', 'Error 13', 'Error 14', 'Error 15', 'Error 16', 'Error 17']
'034'.to_i.to_s(2).rjust(8, '0').chars.each_with_index.map do |bit, index|
bit == '1' ? errors[index] : nil
end.compact
# => ["Error 12", "Error 16"]
For BCD you can make a Hash variable for the states:
states = {
'000' => 'A',
'001' => 'B',
'010' => 'C',
'011' => 'D',
'111' => 'E',
}
bits = '003'.to_i.to_s(2).rjust(8, '0')[-3..-1]
states[bits]
# => 'D'
btw, your markdown tables don't display well...