High/low ruby 中整数的字节转换

High/low byte conversion for integer in ruby

我们在 ruby...

中将数据从十六进制转换为整数时遇到一些小问题

我们得到一个硬件信号,它是整数数据->转换为高低字节,按位反转->字符串。

这是一个例子:

Something between 0 and 75 => will be converted to "0x3938"...

但是如何将“0x3938”转换回 75 之类的值?

我已经试过了:

"0x3938".to_i(16) => 14648 # wrong results (also with "0x3938".hex)

但是这个 returns 错误的值..

有什么提示吗?我不明白这个 high/low 字节拆分?

编辑: 以下是一些示例值,它们都应为 0 - 75 之间的整数。 计算是用 joelparkerhenderson 的答案完成的..

Hex: 0x0000 - calculated integer: 0.0
Hex: 0x0000 - calculated integer: 0.0
Hex: 0x0000 - calculated integer: 0.0
Hex: 0x025d - calculated integer: 186.0
Hex: 0x0ad3 - calculated integer: 203.0
Hex: 0x0fe1 - calculated integer: 135.0
Hex: 0x1508 - calculated integer: 16.0
Hex: 0x1a8a - calculated integer: 81.0
Hex: 0x1f6e - calculated integer: 118.0
Hex: 0x244f - calculated integer: 242.0
Hex: 0x28b2 - calculated integer: 77.0
Hex: 0x2a0a - calculated integer: 80.0
Hex: 0x2aa8 - calculated integer: 21.0
Hex: 0x2ae6 - calculated integer: 103.0
Hex: 0x2add - calculated integer: 187.0
Hex: 0x2adc - calculated integer: 59.0
Hex: 0x2aea - calculated integer: 87.0
Hex: 0x2abf - calculated integer: 253.0
Hex: 0x2a87 - calculated integer: 225.0
Hex: 0x2a4a - calculated integer: 82.0
Hex: 0x2a56 - calculated integer: 106.0
Hex: 0x2a91 - calculated integer: 137.0
Hex: 0x2aee - calculated integer: 119.0
Hex: 0x2b64 - calculated integer: 38.0
Hex: 0x2f41 - calculated integer: 130.0
Hex: 0x32dc - calculated integer: 59.0
Hex: 0x341d - calculated integer: 184.0
Hex: 0x34e7 - calculated integer: 231.0
Hex: 0x35af - calculated integer: 245.0
Hex: 0x369f - calculated integer: 249.0
Hex: 0x377e - calculated integer: 126.0
Hex: 0x3873 - calculated integer: 206.0
Hex: 0x3959 - calculated integer: 154.0
Hex: 0x3a33 - calculated integer: 204.0
Hex: 0x3b4f - calculated integer: 242.0
Hex: 0x3c1b - calculated integer: 216.0

以下内容可能对您有所帮助:

def rbit(n)
  r =  0
  8.times{|i| r = r * 2 + n[i] }
  r
end

信用Reverse bit order of 32 bit integers by mark-hubbart

或者,如果您更喜欢位运算符,则如下所示:

def rbit(n)
  (((n & 0x01) << 7)
  |((n & 0x02) << 5)
  |((n & 0x04) << 3)
  |((n & 0x08) << 1)
  |((n & 0x10) >> 1)
  |((n & 0x20) >> 3)
  |((n & 0x40) >> 5)
  |((n & 0x80) >> 7))
  n
end

信用 Reverse integer bitwise without using loop by paxdiablo

# to convert integer into hexadecimal string
10.to_s(16) => "a"
74.to_s(16) => "4a"
75.to_a(16) => "4b" 

# to convert hexadecimal string into integer   
"4b".hex => 75
"0x4b".hex => 75    
"4b".to_i(16) => 75
"0x4b".to_i(16) => 75

所以"0x3938".to_i(16) => 14648这不是一个错误的值。

对我来说你的第一种方法很好:)

http://ruby-doc.org/core-2.2.0/String.html#method-i-hex