Non-decimal radices/Input: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
(30 intermediate revisions by 21 users not shown)
Line 9:
 
For general number base conversion, see [[Non-decimal radices/Convert]].
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V s = ‘100’
L(base) 2..20
print(‘String '#.' in base #. is #. in base 10’.format(s, base, Int(s, radix' base)))</syntaxhighlight>
 
{{out}}
<pre>
String '100' in base 2 is 4 in base 10
String '100' in base 3 is 9 in base 10
String '100' in base 4 is 16 in base 10
String '100' in base 5 is 25 in base 10
String '100' in base 6 is 36 in base 10
String '100' in base 7 is 49 in base 10
String '100' in base 8 is 64 in base 10
String '100' in base 9 is 81 in base 10
String '100' in base 10 is 100 in base 10
String '100' in base 11 is 121 in base 10
String '100' in base 12 is 144 in base 10
String '100' in base 13 is 169 in base 10
String '100' in base 14 is 196 in base 10
String '100' in base 15 is 225 in base 10
String '100' in base 16 is 256 in base 10
String '100' in base 17 is 289 in base 10
String '100' in base 18 is 324 in base 10
String '100' in base 19 is 361 in base 10
String '100' in base 20 is 400 in base 10
</pre>
 
=={{header|Ada}}==
Line 19 ⟶ 49:
 
numbers.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Numbers is
package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
Line 32 ⟶ 62:
Float_IO.Put (Float'Value ("16#F.FF#E+2"));
Ada.Text_IO.New_Line;
end Numbers;</langsyntaxhighlight>
 
Output:
Line 41 ⟶ 71:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">o_integer(alpha("f4240", 16));
o_byte('\n');
o_integer(alpha("224000000", 5));
Line 51 ⟶ 81:
o_byte('\n');
o_integer(alpha("0xf4240", 0));
o_byte('\n');</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 58 ⟶ 88:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68">main:
(
FILE fbuf; STRING sbuf;
Line 82 ⟶ 112:
printf(($gl$, ABS num)) # prints 666 #
)</langsyntaxhighlight>
Output:
<pre>
Line 90 ⟶ 120:
+666
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">print to :integer "10" ; 10
 
print from.hex "10" ; 16
print from.octal "120" ; 80
print from.binary "10101" ; 21</syntaxhighlight>
 
{{out}}
 
<pre>10
16
80
21</pre>
 
=={{header|AutoHotkey}}==
Line 96 ⟶ 141:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> REM VAL parses decimal strings:
PRINT VAL("0")
PRINT VAL("123456789")
Line 105 ⟶ 150:
PRINT EVAL("%1111111111")
PRINT EVAL("&ABCD")
PRINT EVAL("&FFFFFFFF")</langsyntaxhighlight>
'''Output:'''
<pre>
Line 120 ⟶ 165:
 
In addition to <tt>strtol()</tt> described in the Number base conversion task, you could also use the <code>scanf</code> family of functions to parse un-prefixed hexadecimal, decimal, and octal numbers:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main()
Line 138 ⟶ 183:
 
return 0;
}</langsyntaxhighlight>
 
The <code>strtol()</code> function can also parse prefixed hexadecimal, octal, and decimal strings based on the prefix, when passed a base of 0:
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
Line 165 ⟶ 210:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 183 ⟶ 228:
}
}
}</langsyntaxhighlight>
Output:
<syntaxhighlight lang="text">100 in base 2 is 4 in base 10
100 in base 8 is 64 in base 10
100 in base 10 is 100 in base 10
100 in base 16 is 256 in base 10</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
 
Line 212 ⟶ 258:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(parse-integer "abc" :radix 20 :junk-allowed t) ; => 4232</langsyntaxhighlight>
 
If <code>:radix</code> is omitted, it defaults to 10. If <code>:junk-allowed</code> is omitted, it defaults to <code>nil</code>, causing <code>#'parse-integer</code> to signal an error of type <code>parse-error</code> rather than just returning <code>nil</code> whenever the input string isn't a numeral possibly surrounded by whitespace.
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.conv;
 
void main() {
Line 227 ⟶ 274:
writefln("String '%s' in base %d is %d in base 10" ,
text, base, to!int(text, base));
}</langsyntaxhighlight>
{{out}}
<pre>String '100' in base 2 is 4 in base 10
Line 248 ⟶ 295:
String '100' in base 19 is 361 in base 10
String '100' in base 20 is 400 in base 10</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
Delphi has built in functions that can input numbers in decimal and hexadecimal. Here is simple subroutine that can input number in any radix from 2 to 36.
 
<syntaxhighlight lang="Delphi">
 
function InputByRadix(S: string; Radix: integer): integer;
{Coverts the input string of the specified radix to an integer}
{Accepts digits in the range 0..9 and A..Z and ignores anything else}
var I,B: integer;
begin
Result:=0;
S:=UpperCase(S);
for I:=1 to Length(S) do
begin
if S[I] in ['0'..'9'] then B:=byte(S[I])-$30
else if S[I] in ['A'..'Z'] then B:=byte(S[I])-$41;
Result:=Result * Radix + B;
end;
end;
 
procedure ShowRadixInput(Memo: TMemo);
var Base,I: integer;
begin
for Base:=2 to 20 do
begin
I:=InputByRadix('100',Base);
Memo.Lines.Add(Format('String "100" in base %2D is %3D in Base 10',[Base,I]));
end;
end;
 
</syntaxhighlight>
{{out}}
<pre>
String "100" in base 2 is 4 in Base 10
String "100" in base 3 is 9 in Base 10
String "100" in base 4 is 16 in Base 10
String "100" in base 5 is 25 in Base 10
String "100" in base 6 is 36 in Base 10
String "100" in base 7 is 49 in Base 10
String "100" in base 8 is 64 in Base 10
String "100" in base 9 is 81 in Base 10
String "100" in base 10 is 100 in Base 10
String "100" in base 11 is 121 in Base 10
String "100" in base 12 is 144 in Base 10
String "100" in base 13 is 169 in Base 10
String "100" in base 14 is 196 in Base 10
String "100" in base 15 is 225 in Base 10
String "100" in base 16 is 256 in Base 10
String "100" in base 17 is 289 in Base 10
String "100" in base 18 is 324 in Base 10
String "100" in base 19 is 361 in Base 10
String "100" in base 20 is 400 in Base 10
</pre>
 
 
=={{header|E}}==
Line 253 ⟶ 357:
[[Category:E examples needing attention]] <!-- Is it appropriate to explicitly use __makeInt in this situation, or should it be preferred to import? Does the answer to this change in the presence of a module system? -->
 
<langsyntaxhighlight lang="e">? __makeInt("200", 16)
# value: 512
 
? __makeInt("200", 10)
# value: 200</langsyntaxhighlight>
 
=={{header|Elixir}}==
base: 2 .. 36
<langsyntaxhighlight lang="elixir">iex(1)> String.to_integer("1000")
1000
iex(2)> String.to_integer("1000",2)
Line 270 ⟶ 374:
4096
iex(5)> String.to_integer("ffff",16)
65535</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 279 ⟶ 383:
78300
</pre>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">let value = "100"
let fromBases = [ 2; 8; 10; 16 ]
let values = Seq.initInfinite (fun i -> value)
Seq.zip fromBases (Seq.zip values fromBases |> Seq.map (System.Convert.ToInt32))
|> Seq.iter (
fun (fromBase, valueFromBaseX) ->
printfn "%s in base %i is %i in base 10" value fromBase valueFromBaseX)</syntaxhighlight>
{{out}}
<pre>100 in base 2 is 4 in base 10
100 in base 8 is 64 in base 10
100 in base 10 is 100 in base 10
100 in base 16 is 256 in base 10</pre>
 
=={{header|Factor}}==
Line 292 ⟶ 410:
99
Note that these words are very simple : for example, here's oct> :
<langsyntaxhighlight lang="factor">IN: math.parser
: oct> ( str -- n/f ) 8 base> ; inline</langsyntaxhighlight>
Also, fractions are handled transparently :
( scratchpad ) "1+F/2" hex> .
Line 302 ⟶ 420:
( scratchpad ) "11.1101" bin> .
11.1101
 
=={{header|Forth}}==
Arbitrary base 2-36 parsing is supported by the same mechanism as [[User Input#Forth|decimal parsing]]: set the user variable BASE to the desired base, then scan the number. There are two convenience words for setting the base to DECIMAL or HEX.
<langsyntaxhighlight lang="forth">: parse# ( str len -- u true | false )
0. 2SWAP DUP >R >NUMBER NIP NIP
R> <> DUP 0= IF NIP THEN ;
 
: base# ( str len base -- u true | false )
BASE @ >R BASE ! parse# R> BASE ! ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Example
implicit none
 
Line 335 ⟶ 454:
write(*,*) num ! Prints 666
 
end program</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
FreeBASIC has built-in string to integer conversion functions which automatically recognize numbers in hexadecimal,
decimal, octal or binary format provided that they are prefixed by &H, (nothing), &O and &B respectively. Here's
an example:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim s(1 To 4) As String = {"&H1a", "26", "&O32", "&B11010"} '' 26 in various bases
For i As Integer = 1 To 4
Print s(i); Tab(9); "="; CInt(s(i))
Next
 
Sleep</syntaxhighlight>
 
{{out}}
<pre>
&H1a = 26
26 = 26
&O32 = 26
&B11010 = 26
</pre>
 
=={{header|Free Pascal}}==
Pascal, as defined in ISO 7185, only demands that ''decimal'' integers can be read with <tt>read</tt>/<tt>readLn</tt>.
As an extension, however, the implementation of <tt>read</tt>/<tt>readLn</tt>/<tt>readStr</tt> contained in the standard RTL (run-time library) shipped with FPC (Free Pascal Compiler) supports reading integers that meet the requirements of FreePascal’s own <tt>integer</tt> literal syntax.
Furthermore, <tt>0x</tt>/<tt>0X</tt> is recognized as a hexadecimal base indicator, although in source code it would be illegal.
<syntaxhighlight lang="pascal">
program readIntegers(input, output);
var
i: aluSInt;
begin
while not EOF(input) do
begin
readLn(i);
writeLn(i:24);
end;
end.
</syntaxhighlight>
If the input is too large and cannot be stored in an <tt>integer</tt> (<tt>aluSInt</tt>), a run-time error is generated.
{{out}}
<pre>
$ cat << EOT | ./readIntegers
> -0
> &0644
> $cafeBabe
> 0xdeadBeef
> -0XfF
> -%1010
> 1337
> EOT
0
420
3735928559
-255
-10
1337
</pre>
 
Note, floating-point numbers, the data type <tt>real</tt>, can ''only'' be read in decimal notation.
The minus sign <tt>−</tt> (<tt>U+2212</tt>) is ''not'' recognized.
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 399 ⟶ 579:
fmt.Sscanf("15", "%o", &z)
fmt.Println(&z)
}</langsyntaxhighlight>
Output is all 13s.
 
=={{header|Haskell}}==
Haskell's <tt>read</tt> can parse strings with the same prefix used for literals in Haskell (0x or 0X for hex, 0o or 0O for octal):
<langsyntaxhighlight lang="haskell">Prelude> read "123459" :: Integer
123459
Prelude> read "0xabcf123" :: Integer
180154659
Prelude> read "0o7651" :: Integer
4009</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">READ(Text="123459 ", Format="i10") dec ! 123459
READ(Text=" abcf123 ", Format="Z10") hex ! 180154659
READ(Text=" 7651 ", Format="o10") oct ! 4009
READ(Text=" 101011001", Format="B10.10") bin ! 345</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 421 ⟶ 601:
Icon allows numbers to be defined as 'root' + "R" + 'number', where 'root' is a base from 2 to 36, and 'number' is a string of digits or letters, using 'A' to 'Z' as appropriate for the base; case is ignored. Strings are automatically parsed into numbers when needed, using the procedure 'integer'.
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure convert (str)
write (left(str, 10) || " = " || integer(str))
Line 434 ⟶ 614:
write ("2r1001" + "36r1Z") # shows type conversion, string->integer
end
</syntaxhighlight>
</lang>
 
Output:
Line 447 ⟶ 627:
=={{header|J}}==
 
'''Solution 1''':<langsyntaxhighlight lang="j"> baseN=: (, 'b'&,)&.":</langsyntaxhighlight>
'''Solution 2''' (input sanitizing):<langsyntaxhighlight lang="j"> baseN=: 0&".@,&": 'b' , ] NB. Use if the source of the non-decimal "numbers" is not trustworthy</langsyntaxhighlight>
'''Example''':<langsyntaxhighlight lang="j"> 16 baseN 'abcf123'
180154659
8 baseN '7651'
4009
10 baseN '123459'
123459</langsyntaxhighlight>
'''Note''':
J also provides builtin support for numeric literals of an arbitrary base. The format is ''radix'''''b'''''digits'' (where ''radix'' is specified in base 10). The one restriction is that you cannot use digits larger than 36 ('z'):<langsyntaxhighlight lang="j"> 16babcf123 8b7651 10b123459
180154659 4009 123459</langsyntaxhighlight>
 
However you can use digits larger than the radix:
 
<langsyntaxhighlight lang="j"> 2bhelloworld
17955</langsyntaxhighlight>
 
And you can use bases where not all digits are representable:
 
<langsyntaxhighlight lang="j"> 1000bogus
24016030028</langsyntaxhighlight>
 
Letters used for digits have base 10 values ranging from 10 (a) to 35 (z).
Line 475 ⟶ 655:
 
You must know the base that the String is in before you scan it. Create a <tt>Scanner</tt> in the usual way, but then set its radix to that base (obviously, the default is 10):
<langsyntaxhighlight lang="java5">Scanner sc = new Scanner(System.in); //or any other InputStream or String
sc.useRadix(base); //any number from Character.MIN_RADIX (2) to CHARACTER.MAX_RADIX (36)
sc.nextInt(); //read in a value</langsyntaxhighlight>
Later you can call <tt>sc.reset()</tt> or <tt>sc.useRadix(10)</tt> to undo this change.
 
Another option using the <tt>Integer</tt> class:
<langsyntaxhighlight lang="java">int number = Integer.parseInt(stringNum, base);</langsyntaxhighlight>
The base here has the same restrictions as the <tt>Scanner</tt> example. A similar method is available in the <tt>Long</tt> class. Use no second argument for base 10.
 
If you have a prefixed string ("0x", "0X", or "#" for hex; "0" for octal; otherwise decimal), you can use the <tt>.decode()</tt> utility method to parse the number based on the base indicated by the prefix (note: this returns an Integer object, not a primitive int):
<langsyntaxhighlight lang="java">Integer.decode("0xabcf123"); // hex
Integer.decode("07651"); // octal
Integer.decode("123459"); // decimal</langsyntaxhighlight>
<tt>Long</tt>, <tt>Short</tt>, and <tt>Byte</tt> also have a <tt>.decode()</tt> method, to decode to the appropriate number object type.
 
=={{header|JavaScript}}==
For base 10 and 16 ("0x"-prefixed), (but not 8), it is fastest to parse strings using the unary plus (+) operator:
<langsyntaxhighlight lang="javascript">+"0123459"; // 123459
+"0xabcf123"; // 180154659
 
// also supports negative numbers, but not for hex:
+"-0123459"; // -123459
+"-0xabcf123"; // NaN</langsyntaxhighlight>
See http://www.jibbering.com/faq/notes/type-conversion/#tcNumber for more information.
 
Line 504 ⟶ 684:
<div style='height:40ex; overflow:scroll'>The following examples all return 15:
 
<langsyntaxhighlight lang="javascript">parseInt(" 0xF", 16);
parseInt(" F", 16);
parseInt("17", 8);
Line 515 ⟶ 695:
parseInt("15e2", 10);
parseInt("15px", 10);
parseInt("12", 13);</langsyntaxhighlight>
 
The following examples all return NaN:
 
<langsyntaxhighlight lang="javascript">parseInt("Hello", 8); // Not a number at all
parseInt("546", 2); // Digits are not valid for binary representations</langsyntaxhighlight>
 
The following examples all return -15:
 
<langsyntaxhighlight lang="javascript">parseInt("-F", 16);
parseInt("-0F", 16);
parseInt("-0XF", 16);
Line 533 ⟶ 713:
parseInt("-1111", 2);
parseInt("-15e1", 10);
parseInt("-12", 13);</langsyntaxhighlight>
 
The following example returns 224:
 
<langsyntaxhighlight lang="javascript">parseInt("0e0", 16);</langsyntaxhighlight>
 
Although it is optional, most implementations interpret a numeric string beginning with a leading '0' as octal. The following may have an octal result.
 
<langsyntaxhighlight lang="javascript">parseInt("0e0"); // 0
parseInt("08"); // 0, '8' is not an octal digit.</langsyntaxhighlight></div>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq, and with fq.'''
 
Two filters are provided here for interpreting certain values as decimal numbers:
 
* `ibase($base)` interprets JSON integers and alphanumeric strings (possibly prefixed with one or more "-" signs) as numbers in the given base, and converts them to decimal integers;
* `ibase` also converts its inputs to decimal integers but recognizes the prefixes 0b 0o 0x in the conventional way.
 
In all cases:
* an input string can use any alphanumeric character with its conventional decimal value
** for example `"0bF" | ibase` evaluates to 15, even though "F" is not a binary digit;
* leading and trailing blanks are ignored;
* each leading "-" sign is interpreted as specifying the negative,
** for example: `"--1" | ibase` evaluates to 1;
* `"" | ibase` evaluates to null, and `"-"|ibase` raises an error;
* both filters accept certain JSON numbers in general.
 
<syntaxhighlight lang=jq>
# ibase($base) interprets its input as a number in base $base, and emits the
# corresponding decimal value. $base may be any positive integer.
#
# If the input is a JSON number, and the $base is 10, then the input is simply echoed.
# Otherwise, the input should be a JSON integer or an alphanumeric
# string optionally preceded by one or more occurrences of "-", and
# optionally surrounded by blanks.
# Examples: `"A"|base(2)` => 10
#
def ibase($base):
def tod: if 48 <= . and . <= 57 then . - 48 # 0-9
elif 65 <= . and . <= 90 then . - 55 # A-Z
elif 97 <= . and . <= 122 then . - 87 # a-z
else "ibase cannot handle codepoint \(.)" | error
end;
if type == "number" and $base==10 then .
else
tostring
| sub("^ *";"") | sub(" *$";"") | sub("^0*";"")
| if startswith("-") then - (.[1:] | ibase($base))
else
reduce (tostring|explode|reverse[]) as $point ({value: null, p: 1};
.value += ($point|tod) * .p
| .p *= $base)
| .value
end
end;
 
# After stripping off leading spaces and then leading "-" signs,
# infer the base from the input string as follows:
# prefix 0b for base 2, 0o for base 8, 0x for base 16,
# otherwise base 10
def ibase:
if type=="number" then .
else capture("^ *(?<signs>-*)(?<x>[^ ]*) *$") as $in
| $in.x
| if . == null then null
else (if startswith("0b") then .[2:] | ibase(2)
elif startswith("0o") then .[2:] | ibase(8)
elif startswith("0x") then .[2:] | ibase(16)
else ibase(10)
end) as $y
| if ($in.signs | length) % 2 == 0 then $y else - $y end
end
end;
</syntaxhighlight>
'''Examples'''
 
If your implementation of jq does not support $__loc__ then please adjust the def of assert accordingly.
<syntaxhighlight lang=jq>
# Assertions:
def assert($x; $y):
if ($x == $y) then empty
else "WARNING @ \($__loc__.line): \($x) != \($y)" | stderr, false
end;
def assertions:
assert("" | ibase; null),
assert("--1" | ibase; 1),
assert("11" | ibase(2); 3),
assert(11 | ibase(3); 4),
assert(11 | ibase(14); 15),
assert(" 0xF" | ibase; 15),
assert(" F" | ibase; 15),
assert("17" | ibase(8); 15),
assert("0o17" | ibase; 15),
assert(021 | ibase(7); 15),
assert("015" | ibase(10); 15),
assert(" 0bF "| ibase; 15),
assert("0b1111" | ibase; 15)
;
 
assertions
</syntaxhighlight>
{{output}}
Nada, as expected.
 
=={{header|Julia}}==
<syntaxhighlight lang="julia"># Version 5.2
txt = "100"
for base = 2:21
base10 = parse(Int, txt, base)
println("String $txt in base $base is $base10 in base 10")
end
</syntaxhighlight>
If not specify the base it will figure out the base from the prefix:
<syntaxhighlight lang="julia">
@show parse(Int, "123459")
@show parse(Int, "0xabcf123")
@show parse(Int, "0o7651")
@show parse(Int, "0b101011001")
</syntaxhighlight>
 
{{out}}
<pre>
String 100 in base 2 is 4 in base 10
String 100 in base 3 is 9 in base 10
String 100 in base 4 is 16 in base 10
String 100 in base 5 is 25 in base 10
String 100 in base 6 is 36 in base 10
String 100 in base 7 is 49 in base 10
String 100 in base 8 is 64 in base 10
String 100 in base 9 is 81 in base 10
String 100 in base 10 is 100 in base 10
String 100 in base 11 is 121 in base 10
String 100 in base 12 is 144 in base 10
String 100 in base 13 is 169 in base 10
String 100 in base 14 is 196 in base 10
String 100 in base 15 is 225 in base 10
String 100 in base 16 is 256 in base 10
String 100 in base 17 is 289 in base 10
String 100 in base 18 is 324 in base 10
String 100 in base 19 is 361 in base 10
String 100 in base 20 is 400 in base 10
String 100 in base 21 is 441 in base 10
parse(Int,"123459") = 123459
parse(Int,"0xabcf123") = 180154659
parse(Int,"0o7651") = 4009
parse(Int,"0b101011001") = 345
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
val s = "100"
val bases = intArrayOf(2, 8, 10, 16, 19, 36)
for (base in bases)
println("$s in base ${"%2d".format(base)} is ${s.toInt(base)}")
}</syntaxhighlight>
 
{{out}}
<pre>
100 in base 2 is 4
100 in base 8 is 64
100 in base 10 is 100
100 in base 16 is 256
100 in base 19 is 361
100 in base 36 is 1296
</pre>
 
=={{header|Lua}}==
Lua supports bases between 2 and 36.
<langsyntaxhighlight lang="lua">print( tonumber("123") )
print( tonumber("a5b0", 16) )
print( tonumber("011101", 2) )
print( tonumber("za3r", 36) )</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">19^^91g5dcg2h6da7260a9f3c4a
2^^11110001001000000</syntaxhighlight>
->123456789012345678901234567890
{{out}}
 
<pre>123456789012345678901234567890
2^^11110001001000000
->123456</langpre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">val = sscanf('11 11 11','%d %o %x')</langsyntaxhighlight>
Output:
<pre>val =
Line 564 ⟶ 905:
9
17</pre>
 
=={{header|Nanoquery}}==
Nanoquery can convert numbers with any specified radix value from 2 to 36 using the int() function.
<syntaxhighlight lang="nanoquery">println int("1234")
println int("1100", 2)
println int("abcd", 16)
println int("ghij", 22)</syntaxhighlight>
{{out}}
<pre>1234
12
43981
179011</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
echo parseInt "10" # 10
Line 574 ⟶ 927:
 
echo parseOctInt "0o120" # 80
echo parseOctInt "120" # 80</langsyntaxhighlight>
Output:
<pre>10
Line 584 ⟶ 937:
=={{header|OCaml}}==
The <code>int_of_string</code> function can parse hexadecimal, octal, and binary numbers that have the same prefix that is used to specify OCaml constants ("0x", "0o", and "0b", respectively):
<langsyntaxhighlight lang="ocaml"># int_of_string "123459";;
- : int = 123459
# int_of_string "0xabcf123";;
Line 591 ⟶ 944:
- : int = 4009
# int_of_string "0b101011001";;
- : int = 345</langsyntaxhighlight>
The <code>Int32.of_string</code>, <code>Int64.of_string</code>, and <code>Nativeint.of_string</code> functions also can understand the above prefixes when parsing into their appropriate types.
 
Line 597 ⟶ 950:
 
You could also use the <code>Scanf</code> module to parse un-prefixed hexadecimal, decimal, and octal numbers (binary not supported):
<langsyntaxhighlight lang="ocaml"># Scanf.sscanf "123459" "%d" (fun x -> x);;
- : int = 123459
# Scanf.sscanf "abcf123" "%x" (fun x -> x);;
- : int = 180154659
# Scanf.sscanf "7651" "%o" (fun x -> x);;
- : int = 4009</langsyntaxhighlight>
 
=={{header|Oz}}==
<code>String.toInt</code> understands the usual prefixes. If a string cannot be parsed, an exception will be thrown.
<langsyntaxhighlight lang="oz">{String.toInt "42"} %% decimal
= {String.toInt "0x2a"} %% hexadecimal
= {String.toInt "052"} %% octal
= {String.toInt "0b101010"} %% binary</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Binary conversion is built in to PARI/GP, this script can convert from bases2-36 to bases 2-36. I've had help with this script at http:\\mersenneforums.org . The main flaw in this script I see is that it doesn't allow 36^x-1 type strings, I'll have to add that on later.
<syntaxhighlight lang="parigp">convert(numb1,b1,b2)={
<lang PARI/GP>
convert(numb1,b1,b2)={
my(B=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],a=0,c="");
numb1=Vec(Str(numb1));
Line 629 ⟶ 981:
);
c
};</syntaxhighlight>
};
 
</lang>
Note that version 2.8.0+ supports hexadecimal (0x1ff) and binary (0b10101) inputs. Further, it can accept generic input as a vector:
{{works with|PARI/GP|2.8.0+}}
<syntaxhighlight lang="parigp">fromdigits([1,15,15],16)</syntaxhighlight>
 
=={{header|Pascal}}==
''See [[#Free Pascal|Free Pascal]]''
 
=={{header|Perl}}==
The <tt>hex()</tt> function parses hexadecimal strings. The <tt>oct()</tt> function parses octal strings, as well as hexadecimal, octal, or binary strings with the appropriate prefix ("0x", "0", and "0b", respectively). There is no need to parse decimal strings because in Perl decimal strings and numbers are interchangeable.
<langsyntaxhighlight lang="perl">my $dec = "0123459";
my $hex_noprefix = "abcf123";
my $hex_withprefix = "0xabcf123";
Line 648 ⟶ 1,006:
print oct($oct_withprefix), "\n"; # => 4009
print oct($bin_withprefix), "\n"; # => 345
# nothing for binary without prefix</langsyntaxhighlight>
 
=={{header|Perl 6}}==
By default, all strings of digits are parsed as base 10 numbers, including those with a leading zero. Numbers with a prefix 0b, 0o, 0d or 0x are parsed as binary, octal, decimal or hexadecimal respectively.
<lang perl6>say 0b11011; # -> 27
say 0o11011; # -> 4617
say 0d11011; # -> 11011
say 0x11011; # -> 69649</lang>
 
Additionally, there are built-in adverbial prefix operators to parse strings of "digits" of radix 2 through radix 36 into decimal. They will fail with a runtime error if they are fed a digit that is not valid in that radix.
<lang perl6>my $n = '11011';
 
say :2($n); # -> 27
say :3($n); # -> 112
say :4($n); # -> 325
say :5($n); # -> 756
say :6($n); # -> 1519
say :7($n); # -> 2752
say :8($n); # -> 4617
say :9($n); # -> 7300
say :10($n); # -> 11011
say :11($n); # -> 15984
say :12($n); # -> 22477
say :13($n); # -> 30772
say :14($n); # -> 41175
say :15($n); # -> 54016
say :16($n); # -> 69649
say :17($n); # -> 88452
say :18($n); # -> 110827
say :19($n); # -> 137200
say :20($n); # -> 168021
say :21($n); # -> 203764
say :22($n); # -> 244927
say :23($n); # -> 292032
say :24($n); # -> 345625
say :25($n); # -> 406276
say :26($n); # -> 474579
say :27($n); # -> 551152
say :28($n); # -> 636637
say :29($n); # -> 731700
say :30($n); # -> 837031
say :31($n); # -> 953344
say :32($n); # -> 1081377
say :33($n); # -> 1221892
say :34($n); # -> 1375675
say :35($n); # -> 1543536
say :36($n); # -> 1726309</lang>
 
=={{header|Phix}}==
There are four possible approaches here:<br>
<lang Phix>?scanf("1234","%d")
The entry-level routine for this is to_integer().<br>
?scanf("0b10101010","%d")
The to_number() routine copes with larger numbers, (decimal) fractions, and exponents.<br>
?scanf("#ABCD","%d")
The scanf() routine uses [prefixes and] to_number() internally, but has no explicit base parameter.<br>
?scanf("#FFFFFFFF","%f")
The sledgehammer routines are mpz_set_str() and mpfr_set_str(), with the latter even handling non-decimal fractions.
?scanf("0xFFFFFFFF","%f")
<!--<syntaxhighlight lang="phix">(phixonline)-->
?scanf("0o377","%o")</lang>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
{{out}}
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">to_integer</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1234"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 1234</span>
<pre>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">to_integer</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"10101010"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 170, 0 on failure</span>
{{1234}}
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">to_number</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"FFFFFFFF"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"?"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 4294967295.0, "?" on failure</span>
{{170}}
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"#FFFFFFFF"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%f"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- <nowiki>{{</nowiki>4294967295.0<nowiki>}}</nowiki>, {} on failure</span>
{{43981}}
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0o377"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%o"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- <nowiki>{{</nowiki>255<nowiki>}}</nowiki></span>
{{4294967295}}
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1234"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- <nowiki>{{</nowiki>1234<nowiki>}}</nowiki></span>
{{4294967295}}
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
{{255}}
<span style="color: #004080;">mpz</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
</pre>
<span style="color: #7060A8;">mpz_set_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"377"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">)</span>
Note the need for %f (if you want to get an atom rather than an integer back), and double braces (it's a list of potentially several different possible result sets/interpretations), and that scanf() works best with a few literals (esp spaces but most certainly <b><i>not</i></b> radix prefixes) in the format string.
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "255"</span>
Finally note that while you can use "#DEADBEEF" (without the quotes, ie a fairly big hex number) in a source code file, the compiler will choke on "DEADBEEF", and likewise so too will scanf(), and the only way round that is to insert the right prefix at the right place.
<span style="color: #004080;">mpfr</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">mpfr_set_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"110.01"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "6.25" (which is correct in decimal)</span>
<!--</syntaxhighlight>-->
Aside: the ".0" is a sprint() artefact, to indicate "this is not a Phix 31/63-bit integer". scanf() can return multiple sets of answers. You can of course use mpz_fits_integer() and mpz_get_integer(), mpz_fits_atom() and mpz_get_atom(), mpfr_get_si(), or mpfr_get_d() to retrieve native values from gmp - the mpfr_fits_*() routines are not yet wrapped, give me a shout if they, or a more Phix-friendly version of them, are needed.
 
=={{header|PHP}}==
The <tt>hexdec(), octdec(), bindec()</tt> function parses hexadecimal, octal, and binary strings, respectively. They skip any invalid characters, so a prefix will be ignored. There is no need to parse decimal strings because in PHP decimal strings and numbers are interchangeable.
<langsyntaxhighlight lang="php"><?php
echo +"0123459", "\n"; // prints 123459
echo intval("0123459"), "\n"; // prints 123459
Line 723 ⟶ 1,040:
echo octdec("7651"), "\n"; // prints 4009
echo bindec("101011001"), "\n"; // prints 345
?></langsyntaxhighlight>
 
An undocumented feature of <tt>intval()</tt> is that it can parse prefixed strings when given the base 0:
<langsyntaxhighlight lang="php"><?php
echo intval("123459", 0), "\n"; // prints 123459
echo intval("0xabcf123", 0), "\n"; // prints 180154659
echo intval("07651", 0), "\n"; // prints 4009
?></langsyntaxhighlight>
 
In addition, for hexadecimals, if you have a "0x"-prefixed string, you can just use it in a numeric operation, and it gets converted to the number automatically:
<langsyntaxhighlight lang="php"><?php
echo +"0xabcf123", "\n"; // prints 180154659
# This does not work for octals, however:
echo +"07651", "\n"; // prints 7651
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(de parseNumber (S Base)
(let N 0
(for C (chop S)
(when (> (setq C (- (char C) `(char "0"))) 9)
(dec 'C 39) )
(setq N (+ C (* N Base))) )
N ) )
 
(println (parseNumber "91g5dcg2h6da7260a9f3c4a" 19))</syntaxhighlight>
Output:
<pre>123456789012345678901234567890</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">declare N fixed binary;
get edit (N) (A(7)); /* decimal input of 7 columns */
put skip list (N);
Line 746 ⟶ 1,076:
declare BS bit (32);
get edit (BS) (B(32)); /* Binary input of 32 binary digits. */
put skip edit (BS) (B);</langsyntaxhighlight>
<pre>
23
Line 752 ⟶ 1,082:
</pre>
 
=={{header|PicoLispPowerShell}}==
'''PowerShell parses an integer prefixed with "0x" as hexadecimal. Binary and Octal conversions must use the .NET <code>[Convert]</code>. Here follows a (verbose) example:'''
<lang PicoLisp>(de parseNumber (S Base)
<syntaxhighlight lang="powershell">
(let N 0
function Select-NumberFromString
(for C (chop S)
{
(when (> (setq C (- (char C) `(char "0"))) 9)
[CmdletBinding(DefaultParameterSetName="Decimal")]
(dec 'C 39) )
[OutputType([PSCustomObject])]
(setq N (+ C (* N Base))) )
N ) )Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string]
$InputObject,
 
[Parameter(ParameterSetName="Decimal")]
(println (parseNumber "91g5dcg2h6da7260a9f3c4a" 19))</lang>
[Alias("d","Dec")]
Output:
[switch]
<pre>123456789012345678901234567890</pre>
$Decimal,
 
[Parameter(ParameterSetName="Hexadecimal")]
[Alias("h","Hex")]
[switch]
$Hexadecimal,
 
[Parameter(ParameterSetName="Octal")]
[Alias("o","Oct")]
[switch]
$Octal,
 
[Parameter(ParameterSetName="Binary")]
[Alias("b","Bin")]
[switch]
$Binary
)
 
Begin
{
switch ($PSCmdlet.ParameterSetName)
{
"Decimal" {$base = 10; $pattern = '[+-]?\b[0-9]+\b'; break}
"Hexadecimal" {$base = 16; $pattern = '\b[0-9A-F]+\b' ; break}
"Octal" {$base = 8; $pattern = '\b[0-7]+\b' ; break}
"Binary" {$base = 2; $pattern = '\b[01]+\b' ; break}
"Default" {$base = 10; $pattern = '[+-]?\b[0-9]+\b'; break}
}
}
Process
{
foreach ($object in $InputObject)
{
if ($object -match $pattern)
{
$string = $Matches[0]
}
else
{
$string = $null
}
 
 
try
{
$value = [Convert]::ToInt32($string, $base)
}
catch
{
$value = $null
}
 
[PSCustomObject]@{
Number = $value
String = $string
Base = $base
IsNumber = $value -is [int]
InputString = $object
}
 
}
}
}
</syntaxhighlight>
'''Using a pretend file:'''
<syntaxhighlight lang="powershell">
$file = @'
John Doe abc1 K2hdystkrs
Jane Doe xyz2 Ew3jtdkufy
Joe Blow def3 Ouy1ttluyl
'@ -split [Environment]::NewLine
 
$file | Select-NumberFromString -Hexadecimal | Format-Table
</syntaxhighlight>
{{Out}}
<pre>
Number String Base IsNumber InputString
------ ------ ---- -------- -----------
43969 abc1 16 True John Doe abc1 K2hdystkrs
16 False Jane Doe xyz2 Ew3jtdkufy
57075 def3 16 True Joe Blow def3 Ouy1ttluyl
</pre>
 
=={{Headerheader|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic"> ;Val() parses integer strings
; decimal numbers have no prefix, hexadecimal needs a prefix of '$', binary needs a prefix of '%'
Val("1024102410241024") ; => 1024102410241024
Val("$10FFFFFFFF") ; => 73014444031
Val("%1000") ; => 8</langsyntaxhighlight>
 
=={{header|Python}}==
The [http://docs.python.org/library/functions.html#int int] function will interpret strings as numbers expressed to some base:
<langsyntaxhighlight lang="python">>>> text = '100'
>>> for base in range(2,21):
print ("String '%s' in base %i is %i in base 10"
% (text, base, int(text, base)))
 
String '100' in base 2 is 4 in base 10
String '100' in base 3 is 9 in base 10
Line 798 ⟶ 1,217:
String '100' in base 18 is 324 in base 10
String '100' in base 19 is 361 in base 10
String '100' in base 20 is 400 in base 10</langsyntaxhighlight>
 
In addition, if you give a base of 0, it will try to figure out the base from the prefix, with the same syntax as a numeric literal in Python:
Line 823 ⟶ 1,242:
</pre>
Python 2.6 supports both the above formats, because it supports both types of literals.
 
=={{header|Quackery}}==
 
As a dialogue in the Quackery shell.
 
{{out}}
 
<pre>/O> $ "1234567890" $->n drop ( 'drop' because $->n returns a number AND a success flag )
... echo cr
...
1234567890
 
Stack empty.
 
/O> 19 base put ( parse string as base 19 )
... $ "174B57C7" $->n drop
... base release
... echo cr
...
1234567890
 
Stack empty.
 
/O> 36 base put ( largest base handled by Quackery )
... $ "KF12OI" $->n drop
... base release
... echo cr
...
1234567890
 
Stack empty.</pre>
 
Hexadecimal numbers can be indicated in Quackscript with the builder (compiler directive) <code>hex</code>.
 
<pre>/O> hex 499602D2
...
 
Stack: 1234567890</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r"># parse a string to decimal
as.numeric("20") # 20
# parse a hex-string to decimal
Line 832 ⟶ 1,289:
as.hexmode(as.numeric("32")) # "20"
# parse a string to octal
as.octmode(as.numeric("20")) # "24"</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 853 ⟶ 1,310:
(string->number "1111011" 2))
;; -> '(123 123 123 123 123 123 123 123)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
By default, all strings of digits are parsed as base 10 numbers, including those with a leading zero. Numbers with a prefix 0b, 0o, 0d or 0x are parsed as binary, octal, decimal or hexadecimal respectively.
<syntaxhighlight lang="raku" line>say 0b11011; # -> 27
say 0o11011; # -> 4617
say 0d11011; # -> 11011
say 0x11011; # -> 69649</syntaxhighlight>
 
Additionally, there are built-in adverbial prefix operators to parse strings of "digits" of radix 2 through radix 36 into decimal. They will fail with a runtime error if they are fed a digit that is not valid in that radix.
<syntaxhighlight lang="raku" line>my $n = '11011';
 
say :2($n); # -> 27
say :3($n); # -> 112
say :4($n); # -> 325
say :5($n); # -> 756
say :6($n); # -> 1519
say :7($n); # -> 2752
say :8($n); # -> 4617
say :9($n); # -> 7300
say :10($n); # -> 11011
say :11($n); # -> 15984
say :12($n); # -> 22477
say :13($n); # -> 30772
say :14($n); # -> 41175
say :15($n); # -> 54016
say :16($n); # -> 69649
say :17($n); # -> 88452
say :18($n); # -> 110827
say :19($n); # -> 137200
say :20($n); # -> 168021
say :21($n); # -> 203764
say :22($n); # -> 244927
say :23($n); # -> 292032
say :24($n); # -> 345625
say :25($n); # -> 406276
say :26($n); # -> 474579
say :27($n); # -> 551152
say :28($n); # -> 636637
say :29($n); # -> 731700
say :30($n); # -> 837031
say :31($n); # -> 953344
say :32($n); # -> 1081377
say :33($n); # -> 1221892
say :34($n); # -> 1375675
say :35($n); # -> 1543536
say :36($n); # -> 1726309</syntaxhighlight>
 
=={{header|REXX}}==
Line 868 ⟶ 1,372:
╚══════════════════════════════════════════════════════════════════════════════════╝
</pre>
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates REXX's ability to handle non-decimal radices*/
a=123 /*all of these assignments are identical: */
b='123'
Line 895 ⟶ 1,399:
dd=' + 123'
ee=0000123
ff=1.23e+12
gg=001.23E0002
hh=1230e-1
Line 943 ⟶ 1,447:
b2d: return x2d(b2x(arg(1))) /*convert bin──►dec*/
b2c: return x2c(b2x(arg(1))) /*convert bin──►chr*/
c2b: return word(strip(x2b(c2x(arg(1))),'L',0) 0,1) /*convert chr──►bin*/</langsyntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
see number("0") + nl
see number("123456789") + nl
see number("-987654321") + nl
</syntaxhighlight>
Output:
<pre>
0
123456789
-987654321
</pre>
 
=={{header|RPL}}==
Floating-point numbers can only be entered in decimal format:
3.14
Unsigned integers, which must begin with <code>#</code>, can be expressed in binary, octal, decimal or hexadecimal. A final lowercase letter defines the base.
#100111010b
#472o
#314d
#13Ah
 
=={{header|Ruby}}==
The String class has methods to coerce a string into another form:
<langsyntaxhighlight lang="ruby">dec1 = "0123459"
hex2 = "abcf123"
oct3 = "7651"
Line 955 ⟶ 1,481:
p hex2.hex # => 180154659
p oct3.oct # => 4009
# nothing for binary</langsyntaxhighlight>
 
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.)
<langsyntaxhighlight 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.</langsyntaxhighlight>
 
The '''Integer()''' method can parse a string, provided the string has the right prefix:
<langsyntaxhighlight lang="ruby">p ((Integer(dec1) rescue nil)) # => ArgumentError: invalid value for Integer: "0123459"
p Integer(dec1.sub(/^0+/,"")) # => 123459
p Integer("0d" + dec1) # => 123459
Line 973 ⟶ 1,499:
p Integer("0" + oct3) # => 4009
p Integer("0o" + oct3) # => 4009
p Integer("0b" + bin4) # => 345</langsyntaxhighlight>
 
So can the <code>.to_i(0)</code> method, which never raises an exception:
<langsyntaxhighlight lang="ruby">p dec1.to_i(0) # => 5349 (which is 12345 in octal, the 9 is discarded)
p ("0d" + dec1).to_i(0) # => 123459
p ("0x" + hex2).to_i(0) # => 180154659
p ("0" + oct3).to_i(0) # => 4009
p ("0o" + oct3).to_i(0) # => 4009
p ("0b" + bin4).to_i(0) # => 345</langsyntaxhighlight>
 
And then there's the poorly documented Scanf module in the Ruby stdlib, that seems to wrap the matched value in an array:
<langsyntaxhighlight 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.</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
println!(
"Parse from plain decimal: {}",
"123".parse::<u32>().unwrap()
);
 
println!(
"Parse with a given radix (2-36 supported): {}",
u32::from_str_radix("deadbeef", 16).unwrap()
);
}</syntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">object Main extends App {
 
val (s, bases) = ("100", Seq(2, 8, 10, 16, 19, 36))
bases.foreach(base => println(f"String $s in base $base%2d is $BigInt(s, base)%5d"))
}</syntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">> (string->number "abcf123" 16) ; hex
180154659
> (string->number "123459" 10) ; decimal, the "10" is optional
Line 998 ⟶ 1,544:
4009
> (string->number "101011001" 2) ; binary
345</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 1,004 ⟶ 1,550:
converts a numeric string, with a specified radix, to an [http://seed7.sourceforge.net/manual/types.htm#integer integer].
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: main is func
Line 1,014 ⟶ 1,560:
writeln(integer("tplig0", 32));
writeln(integer("gc0uy9", 36));
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,027 ⟶ 1,573:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var dec = '0123459';
var hex_noprefix = 'abcf123';
var hex_withprefix = '0xabcf123';
Line 1,041 ⟶ 1,587:
say oct_withprefix.oct; # => 4009
say bin_noprefix.bin; # => 345
say bin_withprefix.bin; # => 345</langsyntaxhighlight>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "radices" )
@( description, "This task requires parsing of such a string (which may" )
@( description, "be assumed to contain nothing else) using the" )
@( description, "language's built-in facilities if possible. Parsing of" )
@( description, "decimal strings is required, parsing of other formats" )
@( description, "is optional but should be shown (i.e., if the language" )
@( description, "can parse in base-19 then that should be illustrated)." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Non-decimal_radices/Input" );
pragma license( unrestricted );
 
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
 
procedure radices is
begin
? numerics.value( "16#ABCF123#" );
? numerics.value( "8#7651#" );
? numerics.value( "2#1010011010#" );
? numerics.value( "16#F.FF#E+2" );
end radices;</syntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">- Int.fromString "0123459";
val it = SOME 123459 : int option
- StringCvt.scanString (Int.scan StringCvt.HEX) "0xabcf123";
Line 1,053 ⟶ 1,625:
val it = SOME 4009 : int option
- StringCvt.scanString (Int.scan StringCvt.BIN) "101011001";
val it = SOME 345 : int option</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.6; # For easy scanning of binary
 
# The strings to parse
Line 1,071 ⟶ 1,643:
 
# Print out what happened
puts "$dec1->$v1 $hex2->$v2 $oct3->$v3 $bin4->$v4"</langsyntaxhighlight>
This produces this output:
<pre>0123459->123459 abcf123->180154659 7651->4009 101011001->345</pre>
 
For a general parser up to base 36, a little function can be written:
<langsyntaxhighlight Tcllang="tcl">proc scanbase {str base} {
set res 0
set digits {0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z}
Line 1,085 ⟶ 1,657:
}
return $res
}</langsyntaxhighlight>
Example:
<pre>% scanbase 255 19
Line 1,091 ⟶ 1,663:
% scanbase $dec1 8
bad digit 9</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Conv, Fmt
 
var tests = [ ["0b1110", 2], ["112", 3], ["0o16", 8], ["14", 10], ["0xe", 16], ["e", 19] ]
for (test in tests) {
Fmt.print("$6s in base $-2d = $s", test[0], test[1], Conv.atoi(test[0], test[1]))
} </syntaxhighlight>
 
{{out}}
<pre>
0b1110 in base 2 = 14
112 in base 3 = 14
0o16 in base 8 = 14
14 in base 10 = 14
0xe in base 16 = 14
e in base 19 = 14
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int N; real R;
[Text(8, "123_456");
Line 1,104 ⟶ 1,695:
R:= RlIn(8);
RlOut(0, R); CrLf(0);
]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,114 ⟶ 1,705:
=={{header|zkl}}==
The compiler knows numbers like 0x123, 0b1|101, 0d1_000 but the number conversion functions don't.
<langsyntaxhighlight lang="zkl">fcn b2b(base){
ns:=[20..30].pump(List,T("toString",base));
ns.println();
ns.pump(List,T("toInt",base)).println("\n")
}
b2b(2); b2b(10); b2b(16); b2b(19);</langsyntaxhighlight>
Print 20 .. 30 in binary, decimal, hex & base 19 (or any base 2 .. 32) and parse them to decimal:
{{out}}
9,476

edits