Mega Code Archive

 
Categories / Delphi / Examples
 

Is the a life beyond IntToStr

Title: Is the a life beyond IntToStr? Question: To convert a number into string and back from string, Delphi provides the StrToInt and IntToStr functions or more basicly the Val and Str functions from classic Pascal. But if you need the number in binary, octal or hexadecimal notation, you''re left alone. Answer: The functions convert numbers to strings an back again. The nuber can be converted to any numeric base between 2 and 36. 2 because thats the minimum base and 36 because otherwise we''re out of numbers (0..9 and A..Z used for representing numbers reason). const MinBase = 2; MaxBase = 36; function NumToStr (num, len, base: Integer; neg: Boolean; fill: char): string; // num = the number to convert // len = minimum length of the resulting string // base = numeric base 2 = binary, 8 = octal, 10 = dec, 16 = hex // neg = if treu num is treated as negative number // fill = character that ist used as fill in to get a string // of the length len // // Example: // NumToStr (45, 8, 2, false, ''0'') ''00101101'' // NumToStr (45, 4, 8, false, ''0'') ''0055'' // NumToStr (45, 4, 10, false, '' '') '' 45'' // NumToStr (45, 4, 16, false, ''0'') ''002D'' // NumToStr (45, 0, 36, false, '' '') ''19'' // var s: string; digit: Integer; begin num:= ABS (num); if ((base = MinBase) and (base s:= ''''; repeat digit:= num mod base; if digit else Insert (CHR (digit + 55), s, 1); num:= num div base; until num = 0; if neg then Insert (''-'', s, 1); while Length(s) end; Result:= s; end; Back from String to Number: function StrToNum (const s: string; base: Integer; neg: Boolean; max: Integer): Integer; // s = the string containing the number // base = numeric base that is expected // neg = string maybe contains ''-'' to show if its // max = maximum number that can be containd (normally MaxInt) // // Example: // i:= StrToNum (''00101101'', 2, false, MaxInt); // i:= StrToNum (''002D'', 16, false, MaxInt); // i:= StrToNum (''-45'', 10, true, MaxInt); // i:= StrToNum (''ZZ'', 36, true, MaxInt); // var negate, done: Boolean; i, ind, len, digit, mmb: Integer; c: Char; mdb, res: Integer; begin res:= 0; i:= 1; digit:= 0; if (base = MinBase) and (base mmb:= max mod base; mdb:= max div base; len:= Length (s); negate:= False; while (i if neg then begin case s[i] of ''+'': Inc (i); ''-'': begin Inc (i); negate:= TRUE; end; end; (* CASE *) end; (* IF neg *) done:= len i; while (i c:= Upcase (s[i]); case c of ''0''..''9'': digit:= ORD(c) - 48; ''A''..''Z'': digit:= ORD(c) - 55; else done:= FALSE end; (* CASE *) done:= done and (digit if done then begin done:= (res IF done then begin res:= res * base + digit; Inc (i); end; (* IF done *) end; (* IF done *) end; (* WHILE *) if negate then res:= - res; end; (* IF done *) Result:= res; end;