如何將存盤為字串的大十進制轉換為二進制字串,例如:
'31314232352342341239081370934702357023470' => '10101101110101000011001101011101101001100010100111111100001011'
uj5u.com熱心網友回復:
正如我在評論中指出的那樣,簡單地實作這樣的功能一點也不困難——您只需要創建一個例程來完成您自己使用筆和紙所做的事情。
因此,使用長除法,我設計了以下(相當低效的)代碼:
function DecStrToBinStr(const S: string): string;
procedure DivMod2Str(const S: string; out AQuotient: string; out ARemainder: Integer);
function Digit(C: Char): Integer;
begin
Result := Ord(C) - Ord('0');
end;
function DigitChar(D: Integer): Char;
begin
Result := Char(Ord('0') D);
end;
function NumDig(AIndex: Integer): Integer;
begin
Result := Digit(S[AIndex]);
end;
begin
SetLength(AQuotient, S.Length);
ARemainder := 0;
if AQuotient = '' then
Exit;
var Q := NumDig(1);
for var i := 1 to S.Length do
begin
if not InRange(Ord(S[i]), Ord('0'), Ord('9')) then
raise Exception.Create('Invalid decimal number.');
ARemainder := Ord(Odd(Q));
Q := Q div 2;
AQuotient[i] := DigitChar(Q);
if i < S.Length then
Q := 10*ARemainder NumDig(Succ(i));
end;
while (AQuotient.Length > 1) and (AQuotient[1] = '0') do
Delete(AQuotient, 1, 1);
end;
const
BitStrs: array[Boolean] of Char = ('0', '1');
begin
if S = '' then
Exit('');
var L := TList<Boolean>.Create;
try
var T := S;
var R := 0;
repeat
var Q: string;
DivMod2Str(T, Q, R);
L.Add(R = 1);
T := Q;
until T = '0';
SetLength(Result, L.Count);
for var i := 1 to Result.Length do
Result[i] := BitStrs[L[L.Count - i]];
finally
L.Free;
end;
end;
這是正確的,但肯定不是最有效的實施。
比如按照這個例程,十進制數
30347386718195039666223058436176179389328210368626940040845691245726092139866985
13829421448918578266312873948380914263473944921553341261772026398226410631065331
7294059719089452218
寫成
11101111101001011110010001001010010100100011011010110111111000101000001111010111
00001000000111111000010100100001111100011101001010101110100101101001110100100100
01001010100110001111110111100001100111111111110101111011001001010011101000010010
00001100000001110100000101111111101111011010010011101000001000100111111010100011
10110000001010011110000101101101011101101010101011100010000011000111110010100001
01011010111110101010111100011110100100010110011110011001000100000111001110111010
01110101010100100010100001011101101001011110010110000100111010001101111000100011
111010110000001111111010010111010
以二進制形式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/537868.html
標籤:德尔福帕斯卡拉撒路
