Conv-Decimal to Base

From Vectorlab
Jump to: navigation, search


Converts a decimal number to a given base returning a string. See notes at the end.


NOTE
Result here is a string, otherwise can be a LONGINT, but a string is easier to parse for further use.
  • Use REAL to avoid LONGINT problem: result is easily longer as 10 digits.
  • Really big numbers (> 999999999) resolving in more than 255 chars are rounded, because functions cannot deliver Dynarray of chars.


{ Orso ************************************************ }
{ convert from decimal to base 1-9	
	result here is a string, otherwise can be a longint 
	but a string is easier to parse for further use
	use real to avoid Longint problem: result string is easily longer as 10 digits
	really big numbers (> 999999999) resolving in more than 255 chars are rounded
	because functions cannot deliver Dynarray of chars
	}
FUNCTION U_Dec2Base(n: LONGINT; base, countOfBits: INTEGER): STRING; 
	VAR
		lon : LONGINT;
		str : DYNARRAY OF CHAR;
		
	BEGIN
		str := '';
		
		WHILE n/base <> 0 DO BEGIN
			lon := n MOD base;
			str := Concat(num2str(0, lon), str);
			n := n DIV base;
		END;
		
		{ now the binary could be shorter than the count of digits, add missing zeros }
		WHILE Len(str) < countOfBits DO
			str := Concat('0', str);
		
		U_Dec2Base := str;
	END;