Non-decimal radices/Input: Difference between revisions

m
m (syntax highlighting fixup automation)
m (→‎{{header|Wren}}: Minor tidy)
(6 intermediate revisions by 5 users not shown)
Line 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 666 ⟶ 723:
<syntaxhighlight lang="javascript">parseInt("0e0"); // 0
parseInt("08"); // 0, '8' is not an octal digit.</syntaxhighlight></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}}==
Line 1,089 ⟶ 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}}==
Line 1,270 ⟶ 1,461:
-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}}==
Line 1,388 ⟶ 1,588:
say bin_noprefix.bin; # => 345
say bin_withprefix.bin; # => 345</syntaxhighlight>
 
=={{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}}==
Line 1,440 ⟶ 1,666:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Conv, Fmt
 
var tests = [ ["0b1110", 2], ["112", 3], ["0o16", 8], ["14", 10], ["0xe", 16], ["e", 19] ]
for (test in tests) {
SystemFmt.print("%(Fmt.$6s in base $-2d = $s(6", test[0])) in base %(Fmt.d(-2, test[1])), = %(Conv.atoi(test[0], test[1]))")
} </syntaxhighlight>
 
9,476

edits