Ruby';s字符串#十六进制混淆

Ruby';s字符串#十六进制混淆,ruby,hex,Ruby,Hex,我发现Ruby中的字符串#hex没有为给定的字符返回正确的十六进制值,这很奇怪。我可能误解了这种方法,但以下面的例子为例: 'a'.hex => 10 而“a”的右十六进制值为61: 'a'.unpack('H*') => 61 我错过什么了吗?十六进制是做什么用的?任何提示,谢谢 感谢字符串#hex不提供字符的ASCII索引,它用于将基数为16的数字(十六进制)从字符串转换为整数: % ri String\#hex String#hex (from ruby site) --

我发现Ruby中的字符串#hex没有为给定的字符返回正确的十六进制值,这很奇怪。我可能误解了这种方法,但以下面的例子为例:

'a'.hex
=> 10
而“a”的右十六进制值为61:

'a'.unpack('H*')
=> 61
我错过什么了吗?十六进制是做什么用的?任何提示,谢谢

感谢

字符串#hex
不提供字符的ASCII索引,它用于将基数为16的数字(十六进制)从字符串转换为整数:

% ri String\#hex
String#hex

(from ruby site)
------------------------------------------------------------------------------
  str.hex   -> integer


------------------------------------------------------------------------------

Treats leading characters from str as a string of hexadecimal digits
(with an optional sign and an optional 0x) and returns the
corresponding number. Zero is returned on error.

  "0x0a".hex     #=> 10
  "-1234".hex    #=> -4660
  "0".hex        #=> 0
  "wombat".hex   #=> 0
因此它使用法线映射:

'0'.hex #=> 0
'1'.hex #=> 1
...
'9'.hex #=> 9
'a'.hex #=> 10 == 0xA
'b'.hex #=> 11
...
'f'.hex   #=> 15 == 0xF == 0x0F
'10'.hex  #=> 16 == 0x10
'11'.hex  #=> 17 == 0x11
...
'ff'.hex  #=> 255 == 0xFF
当使用base 16时,它与
String#to_i
非常相似:

'0xff'.to_i(16) #=> 255
'FF'.to_i(16)   #=> 255
'-FF'.to_i(16)  #=> -255
从文档中:

% ri String\#to_i
String#to_i

(from ruby site)
------------------------------------------------------------------------------
  str.to_i(base=10)   -> integer


------------------------------------------------------------------------------

Returns the result of interpreting leading characters in str as an
integer base base (between 2 and 36). Extraneous characters past the
end of a valid number are ignored. If there is not a valid number at the start
of str, 0 is returned. This method never raises an exception
when base is valid.

  "12345".to_i             #=> 12345
  "99 red balloons".to_i   #=> 99
  "0a".to_i                #=> 0
  "0a".to_i(16)            #=> 10
  "hello".to_i             #=> 0
  "1100101".to_i(2)        #=> 101
  "1100101".to_i(8)        #=> 294977
  "1100101".to_i(10)       #=> 1100101
  "1100101".to_i(16)       #=> 17826049

与十六进制方法相比还有一个优势。”10-0'至256


假设您想要比较'100'>'20'。应该返回true,但返回false。使用'100'。十六进制>'20'。十六进制。返回true。哪个更准确

字符的“十六进制值”是什么意思?因为“a”是16的十六进制。你的意思是?“a”是十六进制的10。“f”是十六进制表示16。实际上,“f”是十六进制表示15。答案非常全面。我删除了我以前的答案,因为它毫无意义。谢谢你把一切都说清楚了!