Non-decimal radices/Convert: Difference between revisions

Updated D entries
(Updated D entries)
Line 523:
=={{header|D}}==
===Using Standard Functions===
<lang d>import std.stdio, std.conv, std.string, std.ascii;
 
void main() {
"1abcd".to!int(16).writeln();
 
toLowerwriteln(60_272_032_366.to!string(36), ~ "LetterCase.lower), "' ~',
591_458.to!string(36, LetterCase.lower)).writeln();
}</lang>
{{out}}
<pre>109517
rosetta code</pre>
 
===One Implementation===
<lang d>import std.stdio, std.array, std.ascii;
 
enumimmutable string mDigits = "0123456789abcdefghijklmnopqrstuvwxyz"digits ~ lowercase;
 
ulong atoiRadix(in string str, in intuint radix=10, int* consumed=null) {
nothrow {
static int dtoi(in char dc, in intuint radix) nothrow {
static int[immutable char] digit;
immutable char d = cast(char)toLower(dc).toLower;
if (digit.length == 0) // notNot init yet.
foreach (i, c; mDigits)
digit[c] = i;
Line 549 ⟶ 551:
d in digit && digit[d] < radix)
return digit[d];
return int.min; // aA negative for error.
}
 
Line 556 ⟶ 558:
for (; sp < str.length; sp++) {
immutable int d = dtoi(str[sp], radix);
if (d >= 0) // validValid digit char.
result = radix * result + d;
else
break;
}
if (sp != str.length) // someSome char in str not converted.
sp = -sp;
if (consumed !is null) // signalSignal error if not positive.
*consumed = sp;
return result;
}
 
string itoaRadix(ulong num, in intuint radix=10) pure nothrow
in {
assert(radix > 1 && radix <= mDigits.length);
Line 574 ⟶ 576:
string result;
while (num > 0) {
//immutable intuint d = num % radix;
immutable int d = cast(int)(num % radix);
result = mDigits[d] ~ result;
num = (num - d) / radix;
Line 600 ⟶ 601:
<pre>'1ABcdxyz???' (base 16) = 109517 Converted only: '1ABcd'
rosetta code</pre>
 
===Alternative Implementation===
{{trans|Haskell}}
<lang d>import std.stdio, std.conv, std.algorithm, std.exceptionascii, std.ascii,array;
std.array;
 
alias Digits = ubyte[];
Line 616 ⟶ 617:
}
 
ulongenum fromBase = (in Digits digits, in ubyte base) pure nothrow {=>
return reduce!((n, k) => n * base + k)(00UL, digits);
}
 
stringimmutable fromDigits(inmyDigits Digits= digits) pure~ nothrow {lowercase;
return digits
.map!(d => cast(char)(d < 10 ? d + '0' : d + 'a' - 10))
.array;
}
 
Digitsenum fromDigits = toDigits(in stringDigits numberdigits) pure /*nothrow*/ {=>
digits.map!(d => myDigits[d]).array;
static ubyte convert(in dchar d) pure nothrow {
 
if (d.isDigit) return cast(typeof(return))(d - '0');
enum convert = static ubyte convert(in dchar d) pure nothrow {=>
if (d.isUpper) return cast(typeof(return))(d - 'A' + 10);
cast(ubyte)(d.isDigit ? d - else'0' : return cast(typeof(return))(d.toLower - 'a' + 10);
 
}
enum toDigits = (in returnstring number.map!convert.array;) pure /*nothrow*/ =>
number.map!convert.array;
}
 
void main() {