tags:

views:

107

answers:

1

Is there a Delphi equivalent of the C utoa function, that allows me to provide a radix? I'm using Delphi 2007, and have to read a file which has been named using a radix of 32 with utoa. I'd rather not re-invent the wheel and introduce my own bugs. [Edit:] It would operate the same way that IntToStr operates, which uses base 10 so the equivalent utoa of IntToStr would be utoa(value, 10);

As an example, the integer 100 should return a value of "34".

+3  A: 

Hmm, I did a search of my old code, and found this, which appears to work!

function ItoA(value : Cardinal; Radix : Cardinal) : string;
const
  acCharRef : array  [0 .. 35] of char
  = (
  '0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
  'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
  'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
  'W', 'X', 'Y', 'Z'
  );
var
  nIndex : Integer;
  szBuild : string;
begin
        {* Now loop, taking each digit as modulo radix, and reducing the value
         * by dividing by radix, until the value is zeroed.  Note that
         * at least one loop occurs even if the value begins as 0,
         * since we want "0" to be generated rather than "".
         *}
  szBuild := '';

  repeat
    nIndex := value mod radix;
    szBuild := acCharRef[nIndex] + szBuild;
    value := value div radix;
  until value = 0;

  result := szBuild;
end;
mj2008
Very nice, though you might want a check or an assertion at the top to make sure radix isn't > 35.
Mason Wheeler
Agree w/Mason. A simple one liner at the top would make this safe: Assert(Radix >= 0 and Radix < 36);or, even better to allow for future expansion into unknown radixes <g>: Assert(Radix >= Low(acCharRef) and Radix <= High(acCharRef));
Ken White