Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

BaseToInt() and IntToBase() routines simplified

Title: BaseToInt() and IntToBase() routines simplified. Question: Simplified. Answer: function IntToBase(iValue: integer; Base: byte; Digits: byte = 0): string; function BaseToint(iValue: String; Base: byte): integer; implementation CONST B36 : PChar = ('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'); function IntToBase(iValue: integer; Base: byte; Digits: byte): string; begin result := ''; repeat result := B36[iValue MOD BASE]+result; iValue := iValue DIV Base; until (iValue DIV Base = 0); result := B36[iValue MOD BASE]+result; while length(Result) Result := '0' + Result; end; function BaseToint(iValue: String; Base: byte): integer; var i: byte; begin result := 0; for i := 1 to length(iValue) do begin if (pos(iValue[i], B36)-1) result := result * Base + (pos(iValue[i], B36)-1) else begin result := 0; break; end; end; end;