Non-decimal radices/Input: Difference between revisions

(Add Seed7 example)
Line 870:
bin4 = "101011001"
 
p dec1.to_i # => 123459
p hex2.hex # => 180154659
p oct3.oct # => 4009
# nothing for binary</lang>
 
The IntegerString class canhas parse'''to_i(base)''' amethod string,( providedbase the: string2 has.. the36 right prefix:).
Invalid characters past the end of a valid number are ignored.
<lang ruby>Integer(dec1) # => ArgumentError: invalid value for Integer: "0123459"
(This method never raises an exception when base is valid.)
Integer(dec1.sub(/^0+/,"")) # => 123459
Integer("0x"<lang +ruby>p hex2dec1.to_i(10) # => 180154659 123459
Integerp hex2.to_i("0" + oct316) # => 4009180154659
Integerp oct3.to_i("0b"8) + bin4) # => 345</lang>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:
<lang ruby>p ((Integer(dec1) rescue nil)) # => ArgumentError: invalid value for Integer: "0123459"
p Integer(dec1.sub(/^0+/,"")) # => 123459
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:
<lang ruby>p dec1.to_i(0) # => 5349 (which is 12345 in octal, the 9 is discarded)
dec1.subp (/^0+/,"0d" + dec1).to_i(0) # => 123459
p ("0x" + hex2).to_i(0) # => 180154659
p ("0" + oct3).to_i(0) # => 4009
p ("0b0o" + bin4oct3).to_i(0) # => 345</lang>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:
<lang ruby>require 'scanf'
p dec1.scanf("%d") # => [123459]
p hex2.scanf("%x") # => [180154659]
p oct3.scanf("%o") # => [4009]
# no scanf specifier for binary numbers.</lang>
 
Anonymous user