1 module qui.baseconv;
2 
3 import std.math;
4 import qui.misc;
5 
6 private uinteger toDenary(ushort fromBase, ubyte[] dat){
7 	uinteger r = 0, i = 0;
8 	foreach_reverse(cur; dat){
9 		r += pow(fromBase,i)*cur;
10 		i++;
11 	}
12 	return r;
13 }
14 
15 private ubyte[] fromDenary(ushort toBase, uinteger dat){
16 	ubyte rem;
17 	ubyte[] r;
18 	while (dat>0){
19 		rem = cast(ubyte)dat%toBase;
20 		dat = (dat-rem)/toBase;
21 		r = [rem]~r;
22 	}
23 	
24 	return r;
25 }
26 
27 private string toFormat(ubyte[] ar, char[] rep){
28 	uinteger i;
29 	char[] r;
30 	r.length = ar.length;
31 	for (i=0; i<ar.length; i++){
32 		r[i] = rep[ar[i]];
33 	}
34 	return cast(string)r;
35 }
36 
37 private ubyte[] fromFormat(string ar, char[] rep){
38 	uinteger i;
39 	ubyte[] r;
40 	r.length = ar.length;
41 	for (i=0; i<ar.length; i++){
42 		r[i] = cast(ubyte)strSearch(cast(string)rep, ar[i]);
43 	}
44 	return r;
45 }
46 
47 private uinteger strSearch(string s, char ss){
48 	uinteger i;
49 	for (i=0; i<s.length; i++){
50 		if (s[i]==ss){
51 			break;
52 		}
53 	}
54 	if (i>=s.length){
55 		i = -1;
56 	}
57 	return i;
58 }
59 //exported functions:
60 char[] denToChar(uinteger den){
61 	return cast(char[])fromDenary(256,den);
62 }
63 
64 uinteger charToDen(char[] ch){
65 	return toDenary(256,cast(ubyte[])ch);
66 }
67 
68 uinteger hexToDen(string hex){
69 	ubyte[] buffer;
70 	buffer = fromFormat(hex,cast(char[])"0123456789ABCDEF");
71 	return toDenary(16,buffer);
72 }
73 
74 string denToHex(uinteger den){
75 	ubyte[] buffer;
76 	return toFormat(fromDenary(16,den),cast(char[])"0123456789ABCDEF");
77 }