示範例子至36進位:(含BCB與Delphi版本)
//===== BCB version -------------------------------------------------
AnsiString digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 36 進位
AnsiString DecimalToN(int value, int N, int withZeros=0)
// value:欲轉換的數值; N:欲轉換的進位制;
// withZeros: 總顯示位數,不足前方補零;內定值為0,則依實際位數顯示。
{ AnsiString result="";
if ( N<=0 ) return result;
if ( value==0 ) result="0";
else
{ while( value>0 )
{ result = (AnsiString) digits[1 + value%N] + result;
value /= N;
}
}
while ( result.Length() result = "0" + result;
return (result);
}
int NToDecimal(AnsiString valString, int N)
{ int result=0, index=1;
while( index<=valString.Length() )
{ result = result*N + ( digits.AnsiPos(valString[index]) -1 );
index++;
}
return (result);
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{ AnsiString value;
value = DecimalToN(5438, 16, 5);
ShowMessage(value);
ShowMessage(IntToStr(NToDecimal(value, 16)));
}
//===== Delphi version -------------------------------------------------
const digits :string ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // 36 進位
function DecimalToN(value, N :integer; withZeros :integer =0) :string;
begin
result := '';
if ( N<=0 ) then exit;
if ( value=0 ) then
result:='0'
else
begin
while( value>0 ) do
begin
result := digits[1 + value mod N] + result;
value := value div N;
end
end;
while ( Length(result) result := '0' + result;
end;
function NToDecimal(valString :string; N :integer) : integer;
var
index :integer;
begin
result := 0;
index := 1;
while( index<=Length(valString) ) do
begin
result := result*N + ( AnsiPos(valString[index], digits) -1 );
index := index + 1;;
end
end;
procedure TForm1.Button1Click(Sender: TObject);
var
value : string;
begin
value := DecimalToN(5438, 16, 5);
ShowMessage(value);
ShowMessage(IntToStr(NToDecimal(value, 16)));
end;
RichTop 敬上
轉貼至:http://delphi.ktop.com.tw/board.php?cid=31&fid=79&tid=54631
Delphi有部份程式內容裡截段, 修正如下
//10進位數轉任意整數N進位
function fn_DecimalToN(Value, N :integer; withZeros :integer =0) :string;
begin
result := '';
if ( N<=0 ) then
exit;
if ( Value=0 ) then
result:='0'
else
begin
while( value>0 ) do
begin
result := digits[1 + value mod N] + result;
value := value div N;
end
end;
while (Length(result) < withZeros) do
result := '0' + result;
end;
//10進位數轉任意整數N進位(反轉)
function fn_NToDecimal(valString :string; N :integer) : integer;
var
index :integer;
begin
result := 0;
index := 1;
while(index <= Length(valString) ) do
begin
result := result*N + ( AnsiPos(valString[index], digits) -1 );
index := index + 1;;
end;
end;
沒有留言:
張貼留言