String#hex
static VALUE
rb_str_hex(VALUE str)
{
return rb_str_to_inum(str, 16, FALSE);
}
Interprets the leading substring of self as hexadecimal, possibly signed; returns its value as an integer.
The leading substring is interpreted as hexadecimal when it begins with:
-
One or more character representing hexadecimal digits (each in one of the ranges
'0'..'9','a'..'f', or'A'..'F'); the string to be interpreted ends at the first character that does not represent a hexadecimal digit:Example'f'.hex # => 15 '11'.hex # => 17 'FFF'.hex # => 4095 'fffg'.hex # => 4095 'foo'.hex # => 15 # 'f' hexadecimal, 'oo' not. 'bar'.hex # => 186 # 'ba' hexadecimal, 'r' not. 'deadbeef'.hex # => 3735928559
-
'0x'or'0X', followed by one or more hexadecimal digits:Example'0xfff'.hex # => 4095 '0xfffg'.hex # => 4095
Any of the above may prefixed with '-', which negates the interpreted value:
'-fff'.hex # => -4095 '-0xFFF'.hex # => -4095
For any substring not described above, returns zero:
'xxx'.hex # => 0 ''.hex # => 0
Note that, unlike oct, this method interprets only hexadecimal, and not binary, octal, or decimal notations:
'0b111'.hex # => 45329 '0o777'.hex # => 0 '0d999'.hex # => 55705
Related: See Converting to Non-String.