从字符串转换为十六进制并减去

时间:2015-06-24 00:44:58

标签: ruby string hex

我试图从文件中提取两个十六进制字符串,将它们转换为整数,然后减去:

reg_one = line.strip
reg_one_addr = reg_one[reg_one.index('0x')+2...-1].hex  
puts reg_one_addr  

reg_two = line.strip  
reg_two_addr = reg_two[reg_two.index('0x')+2...-1].hex  
puts reg_two_addr  

diff = reg_two_addr - reg_one_addr  

我这样做时出错:

`-': nil can't be coerced info Fixnum (TypeError) 

我试图从hex转到to_i(16),他们都做同样的事情。我转换后打印出值,它们出来了。我输了。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

reg_one_addr, reg_two_addr =
[reg_one, reg_two].map{|s| s.sub(/.*(?=0x)/, "").hex}

答案 1 :(得分:0)

[reg_one, reg_two].map{|s| eval(s).to_i}.reduce(:-)