Last active
June 29, 2020 08:13
-
-
Save freeonterminate/4cec82e248e557423f5ef2e2ed0b4c5e to your computer and use it in GitHub Desktop.
2進⇔10進数変換
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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