Skip to content

Instantly share code, notes, and snippets.

@freeonterminate
Last active June 29, 2020 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freeonterminate/4cec82e248e557423f5ef2e2ed0b4c5e to your computer and use it in GitHub Desktop.
Save freeonterminate/4cec82e248e557423f5ef2e2ed0b4c5e to your computer and use it in GitHub Desktop.
2進⇔10進数変換
program BinUtils;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.Classes;
function FromBinary(const AValue: String): Integer;
begin
Result := 0;
var Shift := 0;
for var i := AValue.Length - 1 downto 0 do
begin
if AValue.Chars[i] = '1' then
Inc(Result, 1 shl Shift);
Inc(Shift);
end;
end;
function ToBinary(AValue: Integer): String;
const
BIN: array [Boolean] of String = ('0', '1');
begin
Result := '';
var SB := TStringBuilder.Create;
try
while AValue > 0 do
begin
SB.Insert(0, BIN[Odd(AValue)]);
AValue := AValue shr 1;
end;
Result := SB.ToString;
finally
SB.Free;
end;
end;
begin
const NUM = $100;
try
var Bin := ToBinary(NUM);
Writeln('Num: ', NUM);
Writeln('Bin: ', Bin);
Writeln('Dec: ', FromBinary(Bin));
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment