Conv-Base to Decimal

From Vectorlab
Jump to: navigation, search


Converts from a given base to decimal.

{ ************************************************ }
{ convert from base b to decimal }	
{ base is the base from wich to convert }
{ use real to avoid Longint problem: input string is easily longer as 10 digits }
FUNCTION U_Base2DecConverter(str: DYNARRAY OF CHAR; base: INTEGER): REAL;
	VAR
		r1, r2 : REAL;
		i : INTEGER;
		rest : DYNARRAY OF CHAR;
		
	BEGIN
		{ example: 25 base 2 = 11001}
		
		r2 := Str2num(Copy(str, 1, 1)); { init: take first char; 1}
		rest := Copy(str, 2, Len(str) -1); { init: take rest: 1001}
		
		WHILE Len(rest) > 0 DO BEGIN			
			i := Str2num(Copy(rest, 1, 1)); { take 1st char from the rest: 1 (2nd char of original str) }
			r1 := r2 * base + i; { last result * base + 2nd char: 1 * 2 + 1 = 3}
			r2 := r1; { store last result }
			rest := Copy(rest, 2, Len(rest) -1); { remove a digit from the rest: 001}
		END;
		
		U_Base2DecConverter := r1;
	END;