Ruby的String #hex混乱

前端之家收集整理的这篇文章主要介绍了Ruby的String #hex混乱前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我发现 Ruby中的String#hex没有为给定的char返回正确的十六进制值,这很奇怪.我可能误解了该方法,但请采用以下示例:
  1. 'a'.hex
  2. => 10

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

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

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

谢谢

解决方法

String#hex不提供字符的ASCII索引,它用于将字符串的16位数字(十六进制)转换为整数:
  1. % ri String\#hex
  2. String#hex
  3.  
  4. (from ruby site)
  5. ------------------------------------------------------------------------------
  6. str.hex -> integer
  7.  
  8.  
  9. ------------------------------------------------------------------------------
  10.  
  11. Treats leading characters from str as a string of hexadecimal digits
  12. (with an optional sign and an optional 0x) and returns the
  13. corresponding number. Zero is returned on error.
  14.  
  15. "0x0a".hex #=> 10
  16. "-1234".hex #=> -4660
  17. "0".hex #=> 0
  18. "wombat".hex #=> 0

所以它使用法线贴图:

  1. '0'.hex #=> 0
  2. '1'.hex #=> 1
  3. ...
  4. '9'.hex #=> 9
  5. 'a'.hex #=> 10 == 0xA
  6. 'b'.hex #=> 11
  7. ...
  8. 'f'.hex #=> 15 == 0xF == 0x0F
  9. '10'.hex #=> 16 == 0x10
  10. '11'.hex #=> 17 == 0x11
  11. ...
  12. 'ff'.hex #=> 255 == 0xFF

当使用base 16时,它与String#to_i非常相似:

  1. '0xff'.to_i(16) #=> 255
  2. 'FF'.to_i(16) #=> 255
  3. '-FF'.to_i(16) #=> -255

来自文档:

  1. % ri String\#to_i
  2. String#to_i
  3.  
  4. (from ruby site)
  5. ------------------------------------------------------------------------------
  6. str.to_i(base=10) -> integer
  7.  
  8.  
  9. ------------------------------------------------------------------------------
  10.  
  11. Returns the result of interpreting leading characters in str as an
  12. integer base base (between 2 and 36). Extraneous characters past the
  13. end of a valid number are ignored. If there is not a valid number at the start
  14. of str,0 is returned. This method never raises an exception
  15. when base is valid.
  16.  
  17. "12345".to_i #=> 12345
  18. "99 red balloons".to_i #=> 99
  19. "0a".to_i #=> 0
  20. "0a".to_i(16) #=> 10
  21. "hello".to_i #=> 0
  22. "1100101".to_i(2) #=> 101
  23. "1100101".to_i(8) #=> 294977
  24. "1100101".to_i(10) #=> 1100101
  25. "1100101".to_i(16) #=> 17826049

猜你在找的Ruby相关文章