{Convert Hex to Decimal}
RadixStr('FF',
16,
lpBuffer,
10,
Code);
//Should return the string '255' in lpbuffer^.
{Convert Decimal to Binary}
RadixStr('255',
10,
lpBuffer,
2,
Code);
//Should return the string '11111111' in lpbuffer^.
{Convert Hex to Octal}
RadixStr('FF',
16,
lpBuffer,
8,
Code);
//Should return the string '377' in lpbuffer^.
{Function code}
procedure RadixStr(NumStr : pChar;
Radix : LongInt;
ResultStr : pChar;
NewRadix : LongInt;
var ErrorCode : LongInt);
var
RadixChar : array[0..35] of Char;
v : LongInt;
i : LongInt;
p : LongInt;
c : Integer;
begin
if ((Abs(Radix) < 2) or
(Abs(Radix) > 36)) then begin
ErrorCode := p;
Exit;
end;
StrLCopy(ResultStr, NumStr, StrLen(NumStr));
for i := 0 to 35 do begin
if i <= 9 then
RadixChar[i] := Char(48 + (i))
else
RadixChar[i] := Char(64 + (i - 9))
end;
v := 0;
for i := 0 to (StrLen(ResultStr) - 1) do begin
ResultStr[i] := UpCase(ResultStr[i]);
p := Pos(ResultStr[i], PChar(@RadixChar)) - 1;
if ((p < 0) or
(p >= Abs(Radix))) then begin
ErrorCode := i;
Exit;
end;
v := v * Abs(Radix) + p;
end;
if v = 0 then begin
ResultStr := '0';
ErrorCode := 0;
exit;
end else begin
i:=0;
repeat
ResultStr[i] := RadixChar[v mod NewRadix];
v := v div NewRadix;
Inc(i)
until v = 0;
if Radix < 0 then begin
ResultStr[i] := '-';
ResultStr[i + 1] := #0
end else
ResultStr[i] := #0;
p := StrLen(ResultStr);
for i := 0 to ((p div 2) - 1) do begin
ResultStr[i] := Char(Byte(ResultStr[i]) xor
Byte(ResultStr[(p - i) - 1]));
ResultStr[(p - i) - 1] := Char(Byte(ResultStr[(p - i) - 1]) xor
Byte(ResultStr[i]));
ResultStr[i] := Char(Byte(ResultStr[i]) xor
Byte(ResultStr[(p - i) - 1]))
end;
ResultStr[p] := #0;
ErrorCode := 0;
end;
end;