ruby中整数的高/低字节转换

时间:2015-03-14 19:19:09

标签: ruby integer bit-manipulation byte

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

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

这是一个例子:

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

但我怎样才能转换" 0x3938"回到像75这样的东西?

我已经尝试过:

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

但这会返回错误的值..

任何提示?我没有得到这个高/低字节分割?

修改 以下是一些示例值,它们都应该产生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

2 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助:

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

Reverse bit order of 32 bit integers

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

paxdiablo

答案 1 :(得分:0)

# 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