Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
(→{{header|Perl 6}}: add entry) |
(Improved and updated both D entries) |
||
Line 339: | Line 339: | ||
=={{header|D}}== |
=={{header|D}}== |
||
===Using Standard Functions=== |
|||
D standard library string module included functions to convert number to string at a radix. |
|||
<lang d> |
<lang d>import std.stdio, std.conv, std.string; |
||
char[] toString(long value, uint radix); |
|||
char[] toString(ulong value, uint radix);</lang> |
|||
⚫ | |||
<lang d>module radixstring ; |
|||
import std.stdio ; |
|||
import std.ctype ; |
|||
void main() { |
|||
⚫ | |||
"1abcd".to!int(16).writeln(); |
|||
toLower(60_272_032_366.to!string(36) ~ " " ~ |
|||
⚫ | |||
591_458.to!string(36)).writeln(); |
|||
static int[char] digit ; |
|||
}</lang> |
|||
char d = tolower(dc) ; |
|||
{{out}} |
|||
if (digit.length == 0) // not init yet |
|||
<pre>109517 |
|||
⚫ | |||
rosetta code</pre> |
|||
digit[c] = i ; |
|||
⚫ | |||
⚫ | |||
<lang d>import std.stdio, std.array, std.ascii; |
|||
⚫ | |||
if (digit[d] < radix) |
|||
⚫ | |||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
static int[immutable char] digit; |
|||
immutable char d = cast(char)toLower(dc); |
|||
if (digit.length == 0) // not init yet |
|||
⚫ | |||
⚫ | |||
digit[c] = i; |
|||
⚫ | |||
⚫ | |||
d in digit && digit[d] < radix) |
|||
return digit[d]; |
|||
⚫ | |||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
if (d >= 0) // valid digit char |
|||
result = radix * result + d; |
|||
⚫ | |||
break; |
|||
} |
|||
if (sp != str.length) // some char in str not converted. |
|||
sp = -sp; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
string |
string itoaRadix(ulong num, in int radix=10) pure nothrow |
||
in { |
|||
⚫ | |||
assert(radix > 1 && radix <= mDigits.length); |
|||
} body { |
|||
while (num > 0) { |
|||
⚫ | |||
⚫ | |||
while (num > 0) { |
|||
//immutable int d = num % radix; |
|||
immutable int d = cast(int)(num % radix); |
|||
⚫ | |||
result = mDigits[d] ~ result; |
|||
num = (num - d) / radix; |
|||
} |
|||
⚫ | |||
} |
} |
||
void main( |
void main() { |
||
string |
immutable string numStr = "1ABcdxyz???"; |
||
int ate |
int ate; |
||
writef("%s (%d) = %d" |
writef("'%s' (base %d) = %d", numStr, 16, |
||
if(ate <= 0) writefln("\tcheck: %s<%s>",numstr[0..-ate], numstr[-ate..$]) ; |
|||
atoiRadix(numStr, 16, &ate)); |
|||
else writefln() ; |
|||
writefln(ItoA(60272032366,36)," ",ItoA(591458,36)) ; |
|||
⚫ | |||
writefln("\tConverted only: '%s'", numStr[0 .. -ate]); |
|||
⚫ | |||
writeln(); |
|||
writeln(itoaRadix(60_272_032_366, 36), " ", |
|||
itoaRadix(591_458, 36)); |
|||
}</lang> |
}</lang> |
||
{{out}} |
|||
<pre>'1ABcdxyz???' (base 16) = 109517 Converted only: '1ABcd' |
|||
rosetta code<pre> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
<lang e>def stringToInteger := __makeInt |
<lang e>def stringToInteger := __makeInt |