Jestem początkujący i potrzebuje kod który pozwoli na zamiane liczby dziesiętnej na binarną i odwrotnie. Z góry dzięki!
0
0
function IntToBin(Int: int64): string;
var
x, y: int64;
begin
Result := '';
x := Int;
repeat
y := x mod 2;
x := x div 2;
if y > 0 then
Result := '1' + Result
else
Result := '0' + Result;
until x = 0;
end;
function BinToInt64(Bin: string): int64;
var
LengthBin, deleted, i, x: integer;
arr: array of integer;
begin
Result := 0;
if Pos('1', Bin) > 0 then
begin
deleted := 0;
LengthBin := Length(Bin);
repeat
x := Pos('1', Bin);
deleted := deleted + x;
SetLength(arr, Length(arr) + 1);
arr[Length(arr) - 1] := LengthBin - deleted;
Bin := Copy(Bin, x + 1, Length(Bin));
until (Pos('1', Bin) = 0);
for i := 0 to Length(arr) - 1 do
Result := Result + PowerInt(2, arr[i]);
end;
end;
function PowerInt(Base, Exponent: integer): integer;
var
x, i: integer;
begin
if Exponent = 0 then
Result := 1
else if Exponent = 1 then
Result := Base
else
begin
x := Base;
for i := 1 to Exponent - 1 do
Base := Base * x;
Result := Base;
end;
end;
0
Ja bym to napisał troszkę optymalniej :)
Zamiast div i mod można użyć jednej procedury DivMod, ale w tym wypadku znacznie lepsze byłoby zastosowanie and/shr. Analogicznie w drugą stronę and/shl :)
0
Ja bym to napisał troszkę optymalniej :)
Zamiast div i mod można użyć jednej procedury DivMod, ale w tym wypadku znacznie lepsze byłoby zastosowanie and/shr. Analogicznie w drugą stronę and/shl :)
type str64=string[64]; {bo nie masz więcej bitów}
function int2binstr(int:int64):str64;
var b:boolean;
begin
result:='';
repeat
b:=int=0;
result:=char(48+(int and 1))+result;
int:=int shr 1;
until b;
end;
To jedno
function binstr2int(bin:str64):int64;
var i:byte;
begin
i:=byte(bin[0]);
result:=0;
while i>0 do
if bin[i] in [#48,#49]
then
begin
result:=(result shl 1)or byte(bin[i]=#49);
dec(i);
end
else
begin
result:=-i;
break; {błąd w ciągu}
end;
end;
To drugie
Akceptowalne?
0
Ja moze jeszcze napisze ze kiedys Sheitar wrzucil na strone unit z przeliczeniami dec/hex/bin Jak poszukasz to znajdziesz :)