i've found weird string#hex in ruby doesn't return right hex value given char. might misunderstanding method, take following example:
'a'.hex => 10
whereas right hex value 'a' 61:
'a'.unpack('h*') => 61
am missing something? what's hex for? hints appreciated!
thanks
string#hex
doesn't give ascii index of character, it's transforming base-16 number (hexadecimal) string integer:
% ri string\#hex string#hex (from ruby site) ------------------------------------------------------------------------------ str.hex -> integer ------------------------------------------------------------------------------ treats leading characters str string of hexadecimal digits (with optional sign , optional 0x) , returns corresponding number. 0 returned on error. "0x0a".hex #=> 10 "-1234".hex #=> -4660 "0".hex #=> 0 "wombat".hex #=> 0
so uses normal mapping:
'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
it's similar string#to_i
when using base 16:
'0xff'.to_i(16) #=> 255 'ff'.to_i(16) #=> 255 '-ff'.to_i(16) #=> -255
from docs:
% ri string\#to_i string#to_i (from ruby site) ------------------------------------------------------------------------------ str.to_i(base=10) -> integer ------------------------------------------------------------------------------ returns result of interpreting leading characters in str integer base base (between 2 , 36). extraneous characters past end of valid number ignored. if there not valid number @ start of str, 0 returned. method never raises exception when base 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
Comments
Post a Comment