Non-decimal radices/Input: Difference between revisions
Content added Content deleted
(→{{header|Phix}}: completely rewrote entry) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 13: | Line 13: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">V s = ‘100’ |
||
L(base) 2..20 |
L(base) 2..20 |
||
print(‘String '#.' in base #. is #. in base 10’.format(s, base, Int(s, radix' base)))</ |
print(‘String '#.' in base #. is #. in base 10’.format(s, base, Int(s, radix' base)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 49: | Line 49: | ||
numbers.adb: |
numbers.adb: |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
procedure Numbers is |
procedure Numbers is |
||
package Int_IO is new Ada.Text_IO.Integer_IO (Integer); |
package Int_IO is new Ada.Text_IO.Integer_IO (Integer); |
||
Line 62: | Line 62: | ||
Float_IO.Put (Float'Value ("16#F.FF#E+2")); |
Float_IO.Put (Float'Value ("16#F.FF#E+2")); |
||
Ada.Text_IO.New_Line; |
Ada.Text_IO.New_Line; |
||
end Numbers;</ |
end Numbers;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 71: | Line 71: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">o_integer(alpha("f4240", 16)); |
||
o_byte('\n'); |
o_byte('\n'); |
||
o_integer(alpha("224000000", 5)); |
o_integer(alpha("224000000", 5)); |
||
Line 81: | Line 81: | ||
o_byte('\n'); |
o_byte('\n'); |
||
o_integer(alpha("0xf4240", 0)); |
o_integer(alpha("0xf4240", 0)); |
||
o_byte('\n');</ |
o_byte('\n');</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 88: | Line 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]}} |
{{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}} |
{{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}} |
||
< |
<syntaxhighlight lang="algol68">main: |
||
( |
( |
||
FILE fbuf; STRING sbuf; |
FILE fbuf; STRING sbuf; |
||
Line 112: | Line 112: | ||
printf(($gl$, ABS num)) # prints 666 # |
printf(($gl$, ABS num)) # prints 666 # |
||
)</ |
)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 123: | Line 123: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">print to :integer "10" ; 10 |
||
print from.hex "10" ; 16 |
print from.hex "10" ; 16 |
||
print from.octal "120" ; 80 |
print from.octal "120" ; 80 |
||
print from.binary "10101" ; 21</ |
print from.binary "10101" ; 21</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 141: | Line 141: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> REM VAL parses decimal strings: |
||
PRINT VAL("0") |
PRINT VAL("0") |
||
PRINT VAL("123456789") |
PRINT VAL("123456789") |
||
Line 150: | Line 150: | ||
PRINT EVAL("%1111111111") |
PRINT EVAL("%1111111111") |
||
PRINT EVAL("&ABCD") |
PRINT EVAL("&ABCD") |
||
PRINT EVAL("&FFFFFFFF")</ |
PRINT EVAL("&FFFFFFFF")</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
Line 165: | Line 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: |
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: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
int main() |
int main() |
||
Line 183: | Line 183: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
The <code>strtol()</code> function can also parse prefixed hexadecimal, octal, and decimal strings based on the prefix, when passed a base of 0: |
The <code>strtol()</code> function can also parse prefixed hexadecimal, octal, and decimal strings based on the prefix, when passed a base of 0: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <assert.h> |
#include <assert.h> |
||
Line 210: | Line 210: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
class Program |
class Program |
||
Line 228: | Line 228: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<lang>100 in base 2 is 4 in base 10 |
<syntaxhighlight lang="text">100 in base 2 is 4 in base 10 |
||
100 in base 8 is 64 in base 10 |
100 in base 8 is 64 in base 10 |
||
100 in base 10 is 100 in base 10 |
100 in base 10 is 100 in base 10 |
||
100 in base 16 is 256 in base 10</ |
100 in base 16 is 256 in base 10</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <sstream> |
#include <sstream> |
||
Line 258: | Line 258: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(parse-integer "abc" :radix 20 :junk-allowed t) ; => 4232</syntaxhighlight> |
||
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. |
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. |
||
Line 267: | Line 267: | ||
=={{header|D}}== |
=={{header|D}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.conv; |
||
void main() { |
void main() { |
||
Line 274: | Line 274: | ||
writefln("String '%s' in base %d is %d in base 10" , |
writefln("String '%s' in base %d is %d in base 10" , |
||
text, base, to!int(text, base)); |
text, base, to!int(text, base)); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>String '100' in base 2 is 4 in base 10 |
<pre>String '100' in base 2 is 4 in base 10 |
||
Line 300: | Line 300: | ||
[[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? --> |
[[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? --> |
||
< |
<syntaxhighlight lang="e">? __makeInt("200", 16) |
||
# value: 512 |
# value: 512 |
||
? __makeInt("200", 10) |
? __makeInt("200", 10) |
||
# value: 200</ |
# value: 200</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
base: 2 .. 36 |
base: 2 .. 36 |
||
< |
<syntaxhighlight lang="elixir">iex(1)> String.to_integer("1000") |
||
1000 |
1000 |
||
iex(2)> String.to_integer("1000",2) |
iex(2)> String.to_integer("1000",2) |
||
Line 317: | Line 317: | ||
4096 |
4096 |
||
iex(5)> String.to_integer("ffff",16) |
iex(5)> String.to_integer("ffff",16) |
||
65535</ |
65535</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Line 328: | Line 328: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let value = "100" |
||
let fromBases = [ 2; 8; 10; 16 ] |
let fromBases = [ 2; 8; 10; 16 ] |
||
let values = Seq.initInfinite (fun i -> value) |
let values = Seq.initInfinite (fun i -> value) |
||
Line 334: | Line 334: | ||
|> Seq.iter ( |
|> Seq.iter ( |
||
fun (fromBase, valueFromBaseX) -> |
fun (fromBase, valueFromBaseX) -> |
||
printfn "%s in base %i is %i in base 10" value fromBase valueFromBaseX)</ |
printfn "%s in base %i is %i in base 10" value fromBase valueFromBaseX)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>100 in base 2 is 4 in base 10 |
<pre>100 in base 2 is 4 in base 10 |
||
Line 353: | Line 353: | ||
99 |
99 |
||
Note that these words are very simple : for example, here's oct> : |
Note that these words are very simple : for example, here's oct> : |
||
< |
<syntaxhighlight lang="factor">IN: math.parser |
||
: oct> ( str -- n/f ) 8 base> ; inline</ |
: oct> ( str -- n/f ) 8 base> ; inline</syntaxhighlight> |
||
Also, fractions are handled transparently : |
Also, fractions are handled transparently : |
||
( scratchpad ) "1+F/2" hex> . |
( scratchpad ) "1+F/2" hex> . |
||
Line 366: | Line 366: | ||
=={{header|Forth}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="forth">: parse# ( str len -- u true | false ) |
||
0. 2SWAP DUP >R >NUMBER NIP NIP |
0. 2SWAP DUP >R >NUMBER NIP NIP |
||
R> <> DUP 0= IF NIP THEN ; |
R> <> DUP 0= IF NIP THEN ; |
||
: base# ( str len base -- u true | false ) |
: base# ( str len base -- u true | false ) |
||
BASE @ >R BASE ! parse# R> BASE ! ;</ |
BASE @ >R BASE ! parse# R> BASE ! ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">program Example |
||
implicit none |
implicit none |
||
Line 397: | Line 397: | ||
write(*,*) num ! Prints 666 |
write(*,*) num ! Prints 666 |
||
end program</ |
end program</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
Line 403: | Line 403: | ||
decimal, octal or binary format provided that they are prefixed by &H, (nothing), &O and &B respectively. Here's |
decimal, octal or binary format provided that they are prefixed by &H, (nothing), &O and &B respectively. Here's |
||
an example: |
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 |
Dim s(1 To 4) As String = {"&H1a", "26", "&O32", "&B11010"} '' 26 in various bases |
||
Line 410: | Line 410: | ||
Next |
Next |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 424: | Line 424: | ||
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. |
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. |
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); |
program readIntegers(input, output); |
||
var |
var |
||
Line 435: | Line 435: | ||
end; |
end; |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
If the input is too large and cannot be stored in an <tt>integer</tt> (<tt>aluSInt</tt>), a run-time error is generated. |
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}} |
{{out}} |
||
Line 460: | Line 460: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 522: | Line 522: | ||
fmt.Sscanf("15", "%o", &z) |
fmt.Sscanf("15", "%o", &z) |
||
fmt.Println(&z) |
fmt.Println(&z) |
||
}</ |
}</syntaxhighlight> |
||
Output is all 13s. |
Output is all 13s. |
||
=={{header|Haskell}}== |
=={{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): |
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): |
||
< |
<syntaxhighlight lang="haskell">Prelude> read "123459" :: Integer |
||
123459 |
123459 |
||
Prelude> read "0xabcf123" :: Integer |
Prelude> read "0xabcf123" :: Integer |
||
180154659 |
180154659 |
||
Prelude> read "0o7651" :: Integer |
Prelude> read "0o7651" :: Integer |
||
4009</ |
4009</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">READ(Text="123459 ", Format="i10") dec ! 123459 |
||
READ(Text=" abcf123 ", Format="Z10") hex ! 180154659 |
READ(Text=" abcf123 ", Format="Z10") hex ! 180154659 |
||
READ(Text=" 7651 ", Format="o10") oct ! 4009 |
READ(Text=" 7651 ", Format="o10") oct ! 4009 |
||
READ(Text=" 101011001", Format="B10.10") bin ! 345</ |
READ(Text=" 101011001", Format="B10.10") bin ! 345</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Line 544: | Line 544: | ||
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'. |
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) |
procedure convert (str) |
||
write (left(str, 10) || " = " || integer(str)) |
write (left(str, 10) || " = " || integer(str)) |
||
Line 557: | Line 557: | ||
write ("2r1001" + "36r1Z") # shows type conversion, string->integer |
write ("2r1001" + "36r1Z") # shows type conversion, string->integer |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 570: | Line 570: | ||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution 1''':< |
'''Solution 1''':<syntaxhighlight lang="j"> baseN=: (, 'b'&,)&.":</syntaxhighlight> |
||
'''Solution 2''' (input sanitizing):< |
'''Solution 2''' (input sanitizing):<syntaxhighlight lang="j"> baseN=: 0&".@,&": 'b' , ] NB. Use if the source of the non-decimal "numbers" is not trustworthy</syntaxhighlight> |
||
'''Example''':< |
'''Example''':<syntaxhighlight lang="j"> 16 baseN 'abcf123' |
||
180154659 |
180154659 |
||
8 baseN '7651' |
8 baseN '7651' |
||
4009 |
4009 |
||
10 baseN '123459' |
10 baseN '123459' |
||
123459</ |
123459</syntaxhighlight> |
||
'''Note''': |
'''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'):< |
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'):<syntaxhighlight lang="j"> 16babcf123 8b7651 10b123459 |
||
180154659 4009 123459</ |
180154659 4009 123459</syntaxhighlight> |
||
However you can use digits larger than the radix: |
However you can use digits larger than the radix: |
||
< |
<syntaxhighlight lang="j"> 2bhelloworld |
||
17955</ |
17955</syntaxhighlight> |
||
And you can use bases where not all digits are representable: |
And you can use bases where not all digits are representable: |
||
< |
<syntaxhighlight lang="j"> 1000bogus |
||
24016030028</ |
24016030028</syntaxhighlight> |
||
Letters used for digits have base 10 values ranging from 10 (a) to 35 (z). |
Letters used for digits have base 10 values ranging from 10 (a) to 35 (z). |
||
Line 598: | Line 598: | ||
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): |
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): |
||
< |
<syntaxhighlight 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.useRadix(base); //any number from Character.MIN_RADIX (2) to CHARACTER.MAX_RADIX (36) |
||
sc.nextInt(); //read in a value</ |
sc.nextInt(); //read in a value</syntaxhighlight> |
||
Later you can call <tt>sc.reset()</tt> or <tt>sc.useRadix(10)</tt> to undo this change. |
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: |
Another option using the <tt>Integer</tt> class: |
||
< |
<syntaxhighlight lang="java">int number = Integer.parseInt(stringNum, base);</syntaxhighlight> |
||
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. |
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): |
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): |
||
< |
<syntaxhighlight lang="java">Integer.decode("0xabcf123"); // hex |
||
Integer.decode("07651"); // octal |
Integer.decode("07651"); // octal |
||
Integer.decode("123459"); // decimal</ |
Integer.decode("123459"); // decimal</syntaxhighlight> |
||
<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. |
<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}}== |
=={{header|JavaScript}}== |
||
For base 10 and 16 ("0x"-prefixed), (but not 8), it is fastest to parse strings using the unary plus (+) operator: |
For base 10 and 16 ("0x"-prefixed), (but not 8), it is fastest to parse strings using the unary plus (+) operator: |
||
< |
<syntaxhighlight lang="javascript">+"0123459"; // 123459 |
||
+"0xabcf123"; // 180154659 |
+"0xabcf123"; // 180154659 |
||
// also supports negative numbers, but not for hex: |
// also supports negative numbers, but not for hex: |
||
+"-0123459"; // -123459 |
+"-0123459"; // -123459 |
||
+"-0xabcf123"; // NaN</ |
+"-0xabcf123"; // NaN</syntaxhighlight> |
||
See http://www.jibbering.com/faq/notes/type-conversion/#tcNumber for more information. |
See http://www.jibbering.com/faq/notes/type-conversion/#tcNumber for more information. |
||
Line 627: | Line 627: | ||
<div style='height:40ex; overflow:scroll'>The following examples all return 15: |
<div style='height:40ex; overflow:scroll'>The following examples all return 15: |
||
< |
<syntaxhighlight lang="javascript">parseInt(" 0xF", 16); |
||
parseInt(" F", 16); |
parseInt(" F", 16); |
||
parseInt("17", 8); |
parseInt("17", 8); |
||
Line 638: | Line 638: | ||
parseInt("15e2", 10); |
parseInt("15e2", 10); |
||
parseInt("15px", 10); |
parseInt("15px", 10); |
||
parseInt("12", 13);</ |
parseInt("12", 13);</syntaxhighlight> |
||
The following examples all return NaN: |
The following examples all return NaN: |
||
< |
<syntaxhighlight lang="javascript">parseInt("Hello", 8); // Not a number at all |
||
parseInt("546", 2); // Digits are not valid for binary representations</ |
parseInt("546", 2); // Digits are not valid for binary representations</syntaxhighlight> |
||
The following examples all return -15: |
The following examples all return -15: |
||
< |
<syntaxhighlight lang="javascript">parseInt("-F", 16); |
||
parseInt("-0F", 16); |
parseInt("-0F", 16); |
||
parseInt("-0XF", 16); |
parseInt("-0XF", 16); |
||
Line 656: | Line 656: | ||
parseInt("-1111", 2); |
parseInt("-1111", 2); |
||
parseInt("-15e1", 10); |
parseInt("-15e1", 10); |
||
parseInt("-12", 13);</ |
parseInt("-12", 13);</syntaxhighlight> |
||
The following example returns 224: |
The following example returns 224: |
||
< |
<syntaxhighlight lang="javascript">parseInt("0e0", 16);</syntaxhighlight> |
||
Although it is optional, most implementations interpret a numeric string beginning with a leading '0' as octal. The following may have an octal result. |
Although it is optional, most implementations interpret a numeric string beginning with a leading '0' as octal. The following may have an octal result. |
||
< |
<syntaxhighlight lang="javascript">parseInt("0e0"); // 0 |
||
parseInt("08"); // 0, '8' is not an octal digit.</ |
parseInt("08"); // 0, '8' is not an octal digit.</syntaxhighlight></div> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia"># Version 5.2 |
||
txt = "100" |
txt = "100" |
||
for base = 2:21 |
for base = 2:21 |
||
Line 674: | Line 674: | ||
println("String $txt in base $base is $base10 in base 10") |
println("String $txt in base $base is $base10 in base 10") |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
If not specify the base it will figure out the base from the prefix: |
If not specify the base it will figure out the base from the prefix: |
||
< |
<syntaxhighlight lang="julia"> |
||
@show parse(Int, "123459") |
@show parse(Int, "123459") |
||
@show parse(Int, "0xabcf123") |
@show parse(Int, "0xabcf123") |
||
@show parse(Int, "0o7651") |
@show parse(Int, "0o7651") |
||
@show parse(Int, "0b101011001") |
@show parse(Int, "0b101011001") |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 712: | Line 712: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 719: | Line 719: | ||
for (base in bases) |
for (base in bases) |
||
println("$s in base ${"%2d".format(base)} is ${s.toInt(base)}") |
println("$s in base ${"%2d".format(base)} is ${s.toInt(base)}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 733: | Line 733: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Lua supports bases between 2 and 36. |
Lua supports bases between 2 and 36. |
||
< |
<syntaxhighlight lang="lua">print( tonumber("123") ) |
||
print( tonumber("a5b0", 16) ) |
print( tonumber("a5b0", 16) ) |
||
print( tonumber("011101", 2) ) |
print( tonumber("011101", 2) ) |
||
print( tonumber("za3r", 36) )</ |
print( tonumber("za3r", 36) )</syntaxhighlight> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">19^^91g5dcg2h6da7260a9f3c4a |
||
2^^11110001001000000</ |
2^^11110001001000000</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>123456789012345678901234567890 |
<pre>123456789012345678901234567890 |
||
Line 746: | Line 746: | ||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang="matlab">val = sscanf('11 11 11','%d %o %x')</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>val = |
<pre>val = |
||
Line 755: | Line 755: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
Nanoquery can convert numbers with any specified radix value from 2 to 36 using the int() function. |
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("1100", 2) |
||
println int("abcd", 16) |
println int("abcd", 16) |
||
println int("ghij", 22)</ |
println int("ghij", 22)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1234 |
<pre>1234 |
||
Line 766: | Line 766: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import strutils |
||
echo parseInt "10" # 10 |
echo parseInt "10" # 10 |
||
Line 774: | Line 774: | ||
echo parseOctInt "0o120" # 80 |
echo parseOctInt "0o120" # 80 |
||
echo parseOctInt "120" # 80</ |
echo parseOctInt "120" # 80</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>10 |
<pre>10 |
||
Line 784: | Line 784: | ||
=={{header|OCaml}}== |
=={{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): |
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): |
||
< |
<syntaxhighlight lang="ocaml"># int_of_string "123459";; |
||
- : int = 123459 |
- : int = 123459 |
||
# int_of_string "0xabcf123";; |
# int_of_string "0xabcf123";; |
||
Line 791: | Line 791: | ||
- : int = 4009 |
- : int = 4009 |
||
# int_of_string "0b101011001";; |
# int_of_string "0b101011001";; |
||
- : int = 345</ |
- : int = 345</syntaxhighlight> |
||
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. |
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 797: | Line 797: | ||
You could also use the <code>Scanf</code> module to parse un-prefixed hexadecimal, decimal, and octal numbers (binary not supported): |
You could also use the <code>Scanf</code> module to parse un-prefixed hexadecimal, decimal, and octal numbers (binary not supported): |
||
< |
<syntaxhighlight lang="ocaml"># Scanf.sscanf "123459" "%d" (fun x -> x);; |
||
- : int = 123459 |
- : int = 123459 |
||
# Scanf.sscanf "abcf123" "%x" (fun x -> x);; |
# Scanf.sscanf "abcf123" "%x" (fun x -> x);; |
||
- : int = 180154659 |
- : int = 180154659 |
||
# Scanf.sscanf "7651" "%o" (fun x -> x);; |
# Scanf.sscanf "7651" "%o" (fun x -> x);; |
||
- : int = 4009</ |
- : int = 4009</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
<code>String.toInt</code> understands the usual prefixes. If a string cannot be parsed, an exception will be thrown. |
<code>String.toInt</code> understands the usual prefixes. If a string cannot be parsed, an exception will be thrown. |
||
< |
<syntaxhighlight lang="oz">{String.toInt "42"} %% decimal |
||
= {String.toInt "0x2a"} %% hexadecimal |
= {String.toInt "0x2a"} %% hexadecimal |
||
= {String.toInt "052"} %% octal |
= {String.toInt "052"} %% octal |
||
= {String.toInt "0b101010"} %% binary</ |
= {String.toInt "0b101010"} %% binary</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{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. |
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)={ |
||
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=""); |
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)); |
numb1=Vec(Str(numb1)); |
||
Line 828: | Line 828: | ||
); |
); |
||
c |
c |
||
};</ |
};</syntaxhighlight> |
||
Note that version 2.8.0+ supports hexadecimal (0x1ff) and binary (0b10101) inputs. Further, it can accept generic input as a vector: |
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+}} |
{{works with|PARI/GP|2.8.0+}} |
||
< |
<syntaxhighlight lang="parigp">fromdigits([1,15,15],16)</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Line 839: | Line 839: | ||
=={{header|Perl}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="perl">my $dec = "0123459"; |
||
my $hex_noprefix = "abcf123"; |
my $hex_noprefix = "abcf123"; |
||
my $hex_withprefix = "0xabcf123"; |
my $hex_withprefix = "0xabcf123"; |
||
Line 853: | Line 853: | ||
print oct($oct_withprefix), "\n"; # => 4009 |
print oct($oct_withprefix), "\n"; # => 4009 |
||
print oct($bin_withprefix), "\n"; # => 345 |
print oct($bin_withprefix), "\n"; # => 345 |
||
# nothing for binary without prefix</ |
# nothing for binary without prefix</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Line 861: | Line 861: | ||
The scanf() routine uses [prefixes and] to_number() internally, but has no explicit base parameter.<br> |
The scanf() routine uses [prefixes and] to_number() internally, but has no explicit base parameter.<br> |
||
The sledgehammer routines are mpz_set_str() and mpfr_set_str(), with the latter even handling non-decimal fractions. |
The sledgehammer routines are mpz_set_str() and mpfr_set_str(), with the latter even handling non-decimal fractions. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<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> |
<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> |
||
Line 876: | Line 876: | ||
<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: #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> |
<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. |
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}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="php"><?php |
||
echo +"0123459", "\n"; // prints 123459 |
echo +"0123459", "\n"; // prints 123459 |
||
echo intval("0123459"), "\n"; // prints 123459 |
echo intval("0123459"), "\n"; // prints 123459 |
||
Line 887: | Line 887: | ||
echo octdec("7651"), "\n"; // prints 4009 |
echo octdec("7651"), "\n"; // prints 4009 |
||
echo bindec("101011001"), "\n"; // prints 345 |
echo bindec("101011001"), "\n"; // prints 345 |
||
?></ |
?></syntaxhighlight> |
||
An undocumented feature of <tt>intval()</tt> is that it can parse prefixed strings when given the base 0: |
An undocumented feature of <tt>intval()</tt> is that it can parse prefixed strings when given the base 0: |
||
< |
<syntaxhighlight lang="php"><?php |
||
echo intval("123459", 0), "\n"; // prints 123459 |
echo intval("123459", 0), "\n"; // prints 123459 |
||
echo intval("0xabcf123", 0), "\n"; // prints 180154659 |
echo intval("0xabcf123", 0), "\n"; // prints 180154659 |
||
echo intval("07651", 0), "\n"; // prints 4009 |
echo intval("07651", 0), "\n"; // prints 4009 |
||
?></ |
?></syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="php"><?php |
||
echo +"0xabcf123", "\n"; // prints 180154659 |
echo +"0xabcf123", "\n"; // prints 180154659 |
||
# This does not work for octals, however: |
# This does not work for octals, however: |
||
echo +"07651", "\n"; // prints 7651 |
echo +"07651", "\n"; // prints 7651 |
||
?></ |
?></syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de parseNumber (S Base) |
||
(let N 0 |
(let N 0 |
||
(for C (chop S) |
(for C (chop S) |
||
Line 912: | Line 912: | ||
N ) ) |
N ) ) |
||
(println (parseNumber "91g5dcg2h6da7260a9f3c4a" 19))</ |
(println (parseNumber "91g5dcg2h6da7260a9f3c4a" 19))</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>123456789012345678901234567890</pre> |
<pre>123456789012345678901234567890</pre> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pl/i">declare N fixed binary; |
||
get edit (N) (A(7)); /* decimal input of 7 columns */ |
get edit (N) (A(7)); /* decimal input of 7 columns */ |
||
put skip list (N); |
put skip list (N); |
||
Line 923: | Line 923: | ||
declare BS bit (32); |
declare BS bit (32); |
||
get edit (BS) (B(32)); /* Binary input of 32 binary digits. */ |
get edit (BS) (B(32)); /* Binary input of 32 binary digits. */ |
||
put skip edit (BS) (B);</ |
put skip edit (BS) (B);</syntaxhighlight> |
||
<pre> |
<pre> |
||
23 |
23 |
||
Line 931: | Line 931: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
'''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:''' |
'''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:''' |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function Select-NumberFromString |
function Select-NumberFromString |
||
{ |
{ |
||
Line 1,011: | Line 1,011: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Using a pretend file:''' |
'''Using a pretend file:''' |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
$file = @' |
$file = @' |
||
John Doe abc1 K2hdystkrs |
John Doe abc1 K2hdystkrs |
||
Line 1,021: | Line 1,021: | ||
$file | Select-NumberFromString -Hexadecimal | Format-Table |
$file | Select-NumberFromString -Hexadecimal | Format-Table |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,032: | Line 1,032: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic"> ;Val() parses integer strings |
||
; decimal numbers have no prefix, hexadecimal needs a prefix of '$', binary needs a prefix of '%' |
; decimal numbers have no prefix, hexadecimal needs a prefix of '$', binary needs a prefix of '%' |
||
Val("1024102410241024") ; => 1024102410241024 |
Val("1024102410241024") ; => 1024102410241024 |
||
Val("$10FFFFFFFF") ; => 73014444031 |
Val("$10FFFFFFFF") ; => 73014444031 |
||
Val("%1000") ; => 8</ |
Val("%1000") ; => 8</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
The [http://docs.python.org/library/functions.html#int int] function will interpret strings as numbers expressed to some base: |
The [http://docs.python.org/library/functions.html#int int] function will interpret strings as numbers expressed to some base: |
||
< |
<syntaxhighlight lang="python">>>> text = '100' |
||
>>> for base in range(2,21): |
>>> for base in range(2,21): |
||
print ("String '%s' in base %i is %i in base 10" |
print ("String '%s' in base %i is %i in base 10" |
||
Line 1,064: | Line 1,064: | ||
String '100' in base 18 is 324 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 19 is 361 in base 10 |
||
String '100' in base 20 is 400 in base 10</ |
String '100' in base 20 is 400 in base 10</syntaxhighlight> |
||
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: |
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 1,091: | Line 1,091: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r"># parse a string to decimal |
||
as.numeric("20") # 20 |
as.numeric("20") # 20 |
||
# parse a hex-string to decimal |
# parse a hex-string to decimal |
||
Line 1,098: | Line 1,098: | ||
as.hexmode(as.numeric("32")) # "20" |
as.hexmode(as.numeric("32")) # "20" |
||
# parse a string to octal |
# parse a string to octal |
||
as.octmode(as.numeric("20")) # "24"</ |
as.octmode(as.numeric("20")) # "24"</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
#lang racket |
#lang racket |
||
Line 1,119: | Line 1,119: | ||
(string->number "1111011" 2)) |
(string->number "1111011" 2)) |
||
;; -> '(123 123 123 123 123 123 123 123) |
;; -> '(123 123 123 123 123 123 123 123) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(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. |
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 |
<syntaxhighlight lang="raku" line>say 0b11011; # -> 27 |
||
say 0o11011; # -> 4617 |
say 0o11011; # -> 4617 |
||
say 0d11011; # -> 11011 |
say 0d11011; # -> 11011 |
||
say 0x11011; # -> 69649</ |
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. |
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 |
<syntaxhighlight lang="raku" line>my $n = '11011'; |
||
say :2($n); # -> 27 |
say :2($n); # -> 27 |
||
Line 1,166: | Line 1,166: | ||
say :34($n); # -> 1375675 |
say :34($n); # -> 1375675 |
||
say :35($n); # -> 1543536 |
say :35($n); # -> 1543536 |
||
say :36($n); # -> 1726309</ |
say :36($n); # -> 1726309</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 1,181: | Line 1,181: | ||
╚══════════════════════════════════════════════════════════════════════════════════╝ |
╚══════════════════════════════════════════════════════════════════════════════════╝ |
||
</pre> |
</pre> |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates REXX's ability to handle non-decimal radices*/ |
||
a=123 /*all of these assignments are identical: */ |
a=123 /*all of these assignments are identical: */ |
||
b='123' |
b='123' |
||
Line 1,256: | Line 1,256: | ||
b2d: return x2d(b2x(arg(1))) /*convert bin──►dec*/ |
b2d: return x2d(b2x(arg(1))) /*convert bin──►dec*/ |
||
b2c: return x2c(b2x(arg(1))) /*convert bin──►chr*/ |
b2c: return x2c(b2x(arg(1))) /*convert bin──►chr*/ |
||
c2b: return word(strip(x2b(c2x(arg(1))),'L',0) 0,1) /*convert chr──►bin*/</ |
c2b: return word(strip(x2b(c2x(arg(1))),'L',0) 0,1) /*convert chr──►bin*/</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
see number("0") + nl |
see number("0") + nl |
||
see number("123456789") + nl |
see number("123456789") + nl |
||
see number("-987654321") + nl |
see number("-987654321") + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,273: | Line 1,273: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
The String class has methods to coerce a string into another form: |
The String class has methods to coerce a string into another form: |
||
< |
<syntaxhighlight lang="ruby">dec1 = "0123459" |
||
hex2 = "abcf123" |
hex2 = "abcf123" |
||
oct3 = "7651" |
oct3 = "7651" |
||
Line 1,281: | Line 1,281: | ||
p hex2.hex # => 180154659 |
p hex2.hex # => 180154659 |
||
p oct3.oct # => 4009 |
p oct3.oct # => 4009 |
||
# nothing for binary</ |
# nothing for binary</syntaxhighlight> |
||
The String class has '''to_i(base)''' method ( base : 2 .. 36 ). |
The String class has '''to_i(base)''' method ( base : 2 .. 36 ). |
||
Invalid characters past the end of a valid number are ignored. |
Invalid characters past the end of a valid number are ignored. |
||
(This method never raises an exception when base is valid.) |
(This method never raises an exception when base is valid.) |
||
< |
<syntaxhighlight lang="ruby">p dec1.to_i(10) # => 123459 |
||
p hex2.to_i(16) # => 180154659 |
p hex2.to_i(16) # => 180154659 |
||
p oct3.to_i(8) # => 4009 |
p oct3.to_i(8) # => 4009 |
||
p bin4.to_i(2) # => 345 |
p bin4.to_i(2) # => 345 |
||
p "xyz9".to_i(10) # => 0 If there is not a valid letter, 0 is returned.</ |
p "xyz9".to_i(10) # => 0 If there is not a valid letter, 0 is returned.</syntaxhighlight> |
||
The '''Integer()''' method can parse a string, provided the string has the right prefix: |
The '''Integer()''' method can parse a string, provided the string has the right prefix: |
||
< |
<syntaxhighlight lang="ruby">p ((Integer(dec1) rescue nil)) # => ArgumentError: invalid value for Integer: "0123459" |
||
p Integer(dec1.sub(/^0+/,"")) # => 123459 |
p Integer(dec1.sub(/^0+/,"")) # => 123459 |
||
p Integer("0d" + dec1) # => 123459 |
p Integer("0d" + dec1) # => 123459 |
||
Line 1,299: | Line 1,299: | ||
p Integer("0" + oct3) # => 4009 |
p Integer("0" + oct3) # => 4009 |
||
p Integer("0o" + oct3) # => 4009 |
p Integer("0o" + oct3) # => 4009 |
||
p Integer("0b" + bin4) # => 345</ |
p Integer("0b" + bin4) # => 345</syntaxhighlight> |
||
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: |
||
< |
<syntaxhighlight 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 ("0d" + dec1).to_i(0) # => 123459 |
||
p ("0x" + hex2).to_i(0) # => 180154659 |
p ("0x" + hex2).to_i(0) # => 180154659 |
||
p ("0" + oct3).to_i(0) # => 4009 |
p ("0" + oct3).to_i(0) # => 4009 |
||
p ("0o" + oct3).to_i(0) # => 4009 |
p ("0o" + oct3).to_i(0) # => 4009 |
||
p ("0b" + bin4).to_i(0) # => 345</ |
p ("0b" + bin4).to_i(0) # => 345</syntaxhighlight> |
||
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: |
||
< |
<syntaxhighlight lang="ruby">require 'scanf' |
||
p dec1.scanf("%d") # => [123459] |
p dec1.scanf("%d") # => [123459] |
||
p hex2.scanf("%x") # => [180154659] |
p hex2.scanf("%x") # => [180154659] |
||
p oct3.scanf("%o") # => [4009] |
p oct3.scanf("%o") # => [4009] |
||
# no scanf specifier for binary numbers.</ |
# no scanf specifier for binary numbers.</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
println!( |
println!( |
||
"Parse from plain decimal: {}", |
"Parse from plain decimal: {}", |
||
Line 1,327: | Line 1,327: | ||
u32::from_str_radix("deadbeef", 16).unwrap() |
u32::from_str_radix("deadbeef", 16).unwrap() |
||
); |
); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">object Main extends App { |
||
val (s, bases) = ("100", Seq(2, 8, 10, 16, 19, 36)) |
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")) |
bases.foreach(base => println(f"String $s in base $base%2d is $BigInt(s, base)%5d")) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">> (string->number "abcf123" 16) ; hex |
||
180154659 |
180154659 |
||
> (string->number "123459" 10) ; decimal, the "10" is optional |
> (string->number "123459" 10) ; decimal, the "10" is optional |
||
Line 1,344: | Line 1,344: | ||
4009 |
4009 |
||
> (string->number "101011001" 2) ; binary |
> (string->number "101011001" 2) ; binary |
||
345</ |
345</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
Line 1,350: | Line 1,350: | ||
converts a numeric string, with a specified radix, to an [http://seed7.sourceforge.net/manual/types.htm#integer integer]. |
converts a numeric string, with a specified radix, to an [http://seed7.sourceforge.net/manual/types.htm#integer integer]. |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 1,360: | Line 1,360: | ||
writeln(integer("tplig0", 32)); |
writeln(integer("tplig0", 32)); |
||
writeln(integer("gc0uy9", 36)); |
writeln(integer("gc0uy9", 36)); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,373: | Line 1,373: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var dec = '0123459'; |
||
var hex_noprefix = 'abcf123'; |
var hex_noprefix = 'abcf123'; |
||
var hex_withprefix = '0xabcf123'; |
var hex_withprefix = '0xabcf123'; |
||
Line 1,387: | Line 1,387: | ||
say oct_withprefix.oct; # => 4009 |
say oct_withprefix.oct; # => 4009 |
||
say bin_noprefix.bin; # => 345 |
say bin_noprefix.bin; # => 345 |
||
say bin_withprefix.bin; # => 345</ |
say bin_withprefix.bin; # => 345</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">- Int.fromString "0123459"; |
||
val it = SOME 123459 : int option |
val it = SOME 123459 : int option |
||
- StringCvt.scanString (Int.scan StringCvt.HEX) "0xabcf123"; |
- StringCvt.scanString (Int.scan StringCvt.HEX) "0xabcf123"; |
||
Line 1,399: | Line 1,399: | ||
val it = SOME 4009 : int option |
val it = SOME 4009 : int option |
||
- StringCvt.scanString (Int.scan StringCvt.BIN) "101011001"; |
- StringCvt.scanString (Int.scan StringCvt.BIN) "101011001"; |
||
val it = SOME 345 : int option</ |
val it = SOME 345 : int option</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.6; # For easy scanning of binary |
||
# The strings to parse |
# The strings to parse |
||
Line 1,417: | Line 1,417: | ||
# Print out what happened |
# Print out what happened |
||
puts "$dec1->$v1 $hex2->$v2 $oct3->$v3 $bin4->$v4"</ |
puts "$dec1->$v1 $hex2->$v2 $oct3->$v3 $bin4->$v4"</syntaxhighlight> |
||
This produces this output: |
This produces this output: |
||
<pre>0123459->123459 abcf123->180154659 7651->4009 101011001->345</pre> |
<pre>0123459->123459 abcf123->180154659 7651->4009 101011001->345</pre> |
||
For a general parser up to base 36, a little function can be written: |
For a general parser up to base 36, a little function can be written: |
||
< |
<syntaxhighlight lang="tcl">proc scanbase {str base} { |
||
set res 0 |
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} |
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,431: | Line 1,431: | ||
} |
} |
||
return $res |
return $res |
||
}</ |
}</syntaxhighlight> |
||
Example: |
Example: |
||
<pre>% scanbase 255 19 |
<pre>% scanbase 255 19 |
||
Line 1,440: | Line 1,440: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/fmt" for Conv, Fmt |
||
var tests = [ ["0b1110", 2], ["112", 3], ["0o16", 8], ["14", 10], ["0xe", 16], ["e", 19] ] |
var tests = [ ["0b1110", 2], ["112", 3], ["0o16", 8], ["14", 10], ["0xe", 16], ["e", 19] ] |
||
for (test in tests) { |
for (test in tests) { |
||
System.print("%(Fmt.s(6, test[0])) in base %(Fmt.d(-2, test[1])) = %(Conv.atoi(test[0], test[1]))") |
System.print("%(Fmt.s(6, test[0])) in base %(Fmt.d(-2, test[1])) = %(Conv.atoi(test[0], test[1]))") |
||
} </ |
} </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,458: | Line 1,458: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
int N; real R; |
int N; real R; |
||
[Text(8, "123_456"); |
[Text(8, "123_456"); |
||
Line 1,469: | Line 1,469: | ||
R:= RlIn(8); |
R:= RlIn(8); |
||
RlOut(0, R); CrLf(0); |
RlOut(0, R); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,479: | Line 1,479: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
The compiler knows numbers like 0x123, 0b1|101, 0d1_000 but the number conversion functions don't. |
The compiler knows numbers like 0x123, 0b1|101, 0d1_000 but the number conversion functions don't. |
||
< |
<syntaxhighlight lang="zkl">fcn b2b(base){ |
||
ns:=[20..30].pump(List,T("toString",base)); |
ns:=[20..30].pump(List,T("toString",base)); |
||
ns.println(); |
ns.println(); |
||
ns.pump(List,T("toInt",base)).println("\n") |
ns.pump(List,T("toInt",base)).println("\n") |
||
} |
} |
||
b2b(2); b2b(10); b2b(16); b2b(19);</ |
b2b(2); b2b(10); b2b(16); b2b(19);</syntaxhighlight> |
||
Print 20 .. 30 in binary, decimal, hex & base 19 (or any base 2 .. 32) and parse them to decimal: |
Print 20 .. 30 in binary, decimal, hex & base 19 (or any base 2 .. 32) and parse them to decimal: |
||
{{out}} |
{{out}} |