Converting Binary Coded decimal (BCD) to ASCii in ruby
I looking for ruby code to convert BCD to Ascii.I have tried with many codes but i am not getting proper result.
Any suggestions o开发者_C百科r code samples?
I actually wrote a gem for this sort of thing.
https://rubygems.org/gems/bcd
The source code is at https://github.com/dafyddcrosby/ruby_bcd
Although this question is long dead, I just dealt with this. Assuming you've already converted to bcd:
bcd_val.to_s(16)
This converts the bcd value to hex, but because each nibble is a digit, and all digits are between 0-9, it effectively displays as an integer string.
Note that if your bcd number is stored LSB to MSB (depending on how you converted to bcd) the number will display backwards. At that point you can always user str.reverse as necessary.
It is not too clear what do you want to do, but hope that the following can help:
def to_bcd(n)
str = n.to_s
bin = ""
str.each_char do |c|
bin << c.to_i.to_s(2).rjust(4,'0')
end
bin
end
def to_dec(bcd)
n = ""
(bcd.length / 4).times do |i|
n << Integer('0b'+bcd[i*4..(i*4+3)]).to_s
end
n
end
result = to_bcd(120)
p result #=> "000100100000"
p to_dec(result) #=> "120"
p to_dec(result).to_i.chr #=> "x"
If you like, you could extend the Integer and String class with the two methods above, respectively, without arguments and substituting the parameter name with self. But someone does not like the idea to extend standard classes, because it is not a clean/safe programming habit.
精彩评论