Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
(forth) |
(+D) |
||
Line 64: | Line 64: | ||
end Number_Base_Conversion;</ada> |
end Number_Base_Conversion;</ada> |
||
=={{header|D}}== |
|||
D standard library string module included functions to convert number to string at a radix. |
|||
<d>module std.string; |
|||
char[] toString(long value, uint radix); |
|||
char[] toString(ulong value, uint radix);</d> |
|||
Implementation. |
|||
<d>module radixstring ; |
|||
import std.stdio ; |
|||
import std.ctype ; |
|||
const string Digits = "0123456789abcdefghijklmnopqrstuvwxyz" ; |
|||
int dtoi(char dc, int radix) { |
|||
static int[char] digit ; |
|||
char d = tolower(dc) ; |
|||
if (digit.length == 0) // not init yet |
|||
foreach(i,c ; Digits) |
|||
digit[c] = i ; |
|||
if (radix > 1 & radix <= digit.length) |
|||
if (d in digit) |
|||
if (digit[d] < radix) |
|||
return digit[d] ; |
|||
return int.min ; // a negative for error ; |
|||
} |
|||
ulong AtoI(string str, int radix = 10, int* consumed = null) { |
|||
ulong result = 0; |
|||
int sp = 0 ; |
|||
for(; sp < str.length ; sp++) { |
|||
int d = dtoi(str[sp], radix) ; |
|||
if (d >= 0) // valid digit char |
|||
result = radix*result + d ; |
|||
else |
|||
break ; |
|||
} |
|||
if(sp != str.length) // some char in str not converted |
|||
sp = -sp ; |
|||
if (!(consumed is null)) // signal error if not positive ; |
|||
*consumed = sp ; |
|||
return result ; |
|||
} |
|||
string ItoA(ulong num, int radix = 10) { |
|||
string result = null ; |
|||
// if (radix < 2 || radix > Digits.length) throw Error |
|||
while (num > 0) { |
|||
int d = num % radix ; |
|||
result = Digits[d]~ result ; |
|||
num = (num - d) / radix ; |
|||
} |
|||
return result == null ? "0" : result ; |
|||
} |
|||
void main(string[] args) { |
|||
string numstr = "1ABcdxyz???" ; |
|||
int ate ; |
|||
writef("%s (%d) = %d",numstr, 16, AtoI(numstr, 16, &ate)) ; |
|||
if(ate <= 0) writefln("\tcheck: %s<%s>",numstr[0..-ate], numstr[-ate..$]) ; |
|||
else writefln() ; |
|||
writefln(ItoA(60272032366,36)," ",ItoA(591458,36)) ; |
|||
}</d> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Forth has a global user variable, BASE, which determines the radix used for parsing, interpretation, and printing of integers. This can handle bases from 2-36, but there are two words to switch to the most popular bases, DECIMAL and HEX. |
Forth has a global user variable, BASE, which determines the radix used for parsing, interpretation, and printing of integers. This can handle bases from 2-36, but there are two words to switch to the most popular bases, DECIMAL and HEX. |