Simple answer: It's because 0a
or a
in Hexadecimal is equal to 10
in Decimal.
And base
, in other word Radix means the number of unique digits in a numeral system.
In Decimal, we have 0
to 9
, 10 digits to represent numbers.
In Hexadecimal, there're 16 digits instead, apart from 0
to 9
, we use a
to f
to represent the conceptual numbers of 10
to 15
.
You can test it like this:
"a".to_i(16)
#=> 10
"b".to_i(16)
#=> 11
"f".to_i(16)
#=> 15
"g".to_i(16)
#=> 0 # Because it's not a correct hexadecimal digit/number.
'2c'.to_i(16)
#=> 44
'2CH2'.to_i(16)
#=> 44 # Extraneous characters past the end of a valid number are ignored, and it's case insensitive.
9.to_s.to_i(16)
#=> 9
10.to_s.to_i(16)
#=> 16
In other words, 10
in Decimal is equal to a
in Hexadecimal.
And 10
in Hexadecimal is equal to 16
in Decimal. (Doc for to_i)
Note that usually we use 0x
precede to Hexadecimal numbers:
"0xa".to_i(16)
#=> 10
"0x100".to_i(16)
#=> 256
Btw, you can just use these representations in Ruby:
num_hex = 0x100
#=> 256
num_bin = 0b100
#=> 4
num_oct = 0o100
#=> 64
num_dec = 0d100
#=> 100
Hexadecimal, binary, octonary, decimal (this one, 0d
is superfluous of course, just use in some cases for clarification.)