Converting Between Numeric Bases

Problem

You want to convert numbers from one base to another.

Solution

You can convert specific binary, octal, or hexadecimal numbers to decimal by representing them with the 0b, 0o, or 0x prefixes:

0b100 # => 4 0o100 # => 64 0x100 # => 256

You can also convert between decimal numbers and string representations of those numbers in any base from 2 to 36. Simply pass the base into String#to_i or Integer#to_s.

Here are some conversions between string representations of numbers in various bases, and the corresponding decimal numbers:

"1045".to_i(10) # => 1045 "-1001001".to_i(2) # => -73 "abc".to_i(16) # => 2748 "abc".to_i(20) # => 4232 "number".to_i(36) # => 1442151747 "zz1z".to_i(36) # => 1678391 "abcdef".to_i(16) # => 11259375 "AbCdEf".to_i(16) # => 11259375

Here are some reverse conversions of decimal numbers to the strings that represent those numbers in various bases:

42.to_s(10) # => "42" -100.to_s(2) # => "-1100100" 255.to_s(16) # => "ff" 1442151747.to_s(36) # => "number"

Some invalid conversions:

"6".to_i(2) # => 0 "0".to_i(1) # ArgumentError: illegal radix 1 40.to_s(37) # ArgumentError: illegal radix 37

 

Discussion

String#to_i can parse and Integer#to_s can create a string representation in every common integer base: from binary (the familiar base 2, which uses only the digits 0 and 1) to hexatridecimal (base 36). Hexatridecimal uses the digits 09 and the letters az; it's sometimes used to generate alphanumeric mneumonics for long numbers.

The only commonly used counting systems with bases higher than 36 are the variants of base-64 encoding used in applications like MIME mail attachments. These usually encode strings, not numbers; to encode a string in MIME-style base-64, use the base64 library.

See Also

Категории