Non-decimal radices/Input: Difference between revisions
Content added Content deleted
(Add Seed7 example) |
|||
Line 870: | Line 870: | ||
bin4 = "101011001" |
bin4 = "101011001" |
||
dec1.to_i # => 123459 |
p dec1.to_i # => 123459 |
||
hex2.hex # => 180154659 |
p hex2.hex # => 180154659 |
||
oct3.oct # => 4009 |
p oct3.oct # => 4009 |
||
# nothing for binary</lang> |
# nothing for binary</lang> |
||
The |
The String class has '''to_i(base)''' method ( base : 2 .. 36 ). |
||
Invalid characters past the end of a valid number are ignored. |
|||
⚫ | |||
(This method never raises an exception when base is valid.) |
|||
⚫ | |||
<lang ruby>p dec1.to_i(10) # => 123459 |
|||
p hex2.to_i(16) # => 180154659 |
|||
p oct3.to_i(8) # => 4009 |
|||
p bin4.to_i(2) # => 345 |
|||
p "xyz9".to_i(10) # => 0 If there is not a valid letter, 0 is returned.</lang> |
|||
The '''Integer()''' method can parse a string, provided the string has the right prefix: |
|||
⚫ | |||
⚫ | |||
p Integer("0d" + dec1) # => 123459 |
|||
p Integer("0x" + hex2) # => 180154659 |
|||
p Integer("0" + oct3) # => 4009 |
|||
p Integer("0o" + oct3) # => 4009 |
|||
p Integer("0b" + bin4) # => 345</lang> |
|||
So can the <code>.to_i(0)</code> method, which never raises an exception: |
So can the <code>.to_i(0)</code> method, which never raises an exception: |
||
<lang ruby>dec1.to_i(0) # => 5349 (which is 12345 in octal, the 9 is discarded) |
<lang ruby>p dec1.to_i(0) # => 5349 (which is 12345 in octal, the 9 is discarded) |
||
p ("0d" + dec1).to_i(0) # => 123459 |
|||
("0x" + hex2).to_i(0) # => 180154659 |
p ("0x" + hex2).to_i(0) # => 180154659 |
||
("0" + oct3).to_i(0) # => 4009 |
p ("0" + oct3).to_i(0) # => 4009 |
||
(" |
p ("0o" + oct3).to_i(0) # => 4009 |
||
p ("0b" + bin4).to_i(0) # => 345</lang> |
|||
And then there's the poorly documented Scanf module in the Ruby stdlib, that seems to wrap the matched value in an array: |
And then there's the poorly documented Scanf module in the Ruby stdlib, that seems to wrap the matched value in an array: |
||
<lang ruby>require 'scanf' |
<lang ruby>require 'scanf' |
||
dec1.scanf("%d") # => [123459] |
p dec1.scanf("%d") # => [123459] |
||
hex2.scanf("%x") # => [180154659] |
p hex2.scanf("%x") # => [180154659] |
||
oct3.scanf("%o") # => [4009] |
p oct3.scanf("%o") # => [4009] |
||
# no scanf specifier for binary numbers.</lang> |
# no scanf specifier for binary numbers.</lang> |
||