微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ruby的String #hex混乱

我发现 Ruby中的String#hex没有为给定的char返回正确的十六进制值,这很奇怪.我可能误解了该方法,但请采用以下示例:
'a'.hex
=> 10

而’a’的正确十六进制值为61:

'a'.unpack('H*')
=> 61

我错过了什么吗?什么是十六进制?任何提示赞赏!

谢谢

解决方法

String#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

原文地址:https://www.jb51.cc/ruby/268280.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐