IntToStr and StrToInt are nice functions, but if you are dealing with other number systems then binarie, decimal or sedecimal you have to do this by yourself. Here is a solution for this.
The following two functions convert numbers to strings and back again. The number can be converted to any numeric base between 2 and 36. 2 because thats the minimum base (binary) and 36 because otherwise we´re out of numbers - 0..9 and A..Z used for representing numbers.
This one converts a number to its string representation:
const MinBase = 2; MaxBase = 36; function NumToStr (num, len, base: Integer;This is the counterpart to the function above. It converts a string containing an number into its numerical value:
neg: Boolean; fill: char): string; // num = the number to convert // len = minimum length of the resulting string // base = numeric base // 2 = bin, 8 = octal, 10 = dec, 16 = hex // neg = if true num is treated as negativ // 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 <= MaxBase)) then begin s:= ''; repeat digit:= num mod base; if digit < 10 then Insert (CHR (digit + 48), s, 1) else Insert (CHR (digit + 55), s, 1); num:= num div base; until num = 0; if neg then Insert ('-', s, 1); while Length(s) < len do Insert (fill, s, 1); end; Result:= s; end;
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 can contain ‘-’ to show if < 0 // max = maximum number that can be contained // // 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 <= MaxBase) then begin mmb:= max mod base; mdb:= max div base; len:= Length (s); negate:= False; while (i <= len) and (s[i] = '') do Inc (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 <= len) and done do begin 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 < base); if done then begin done:= (res < mdb) or ((res = mdb) and (digit <= mmb)); 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;