Skip to content

Instantly share code, notes, and snippets.

@dominik-hadl
Created November 8, 2014 19:44
Show Gist options
  • Save dominik-hadl/42a7e518f43d24a892ad to your computer and use it in GitHub Desktop.
Save dominik-hadl/42a7e518f43d24a892ad to your computer and use it in GitHub Desktop.
Converts a decimal number in a string to binary (from input file CISLA.IN to output file CISLA.OUT, one number on each line).
program BinaryConvertor;
{ ----------------------------------------------------------- }
uses
Sysutils;
{ ----------------------------------------------------------- }
{ DIVIDE BY TWO }
// This functions takes a decimal string and divides it by two
function dividedByTwo(Input: String): String;
var
newString, finalString: String;
add, next, len, i, a, zeros: Longint;
begin
next := 0;
zeros := 0;
// get the input string length and prepare new one
len := Length(Input);
SetLength(newString, len);
// divide the string by two
for i := 1 to len do
begin
add := next;
a := Ord(Input[i]) - Ord('0');
if Odd(a) then next := 5
else next := 0;
a := (a div 2) + add;
newString[i] := Char(a + Ord('0'));
end;
// count all leading zeros
if len > 1 then
begin
for i := 1 to len do
begin
if newString[i] = '0'
then zeros += 1
else break;
end;
end;
// trim leading zeros (if any)
if zeros > 0 then
begin
SetLength(finalString, len - zeros);
for i := (zeros + 1) to len do
begin
finalString[i - zeros] := newString[i];
end;
end
else finalString := newString;
dividedByTwo := finalString;
end;
{ ----------------------------------------------------------- }
{ MAIN }
procedure Main();
var
InFile, OutFile: Text;
Decimal, Binary: String;
len, last: Longint;
begin
Assign(InFile, GetCurrentDir + '/CISLA.IN');
Assign(OutFile, GetCurrentDir + '/CISLA.OUT');
// open for reading
Reset(InFile);
// open for writing
Rewrite(OutFile);
repeat
Readln(InFile, Decimal);
Binary := '';
// until the number is zero divide and convert
while not (Decimal[1] = '0') do
begin
len := Length(Decimal);
last := Ord(Decimal[len]) - Ord('0');
if Odd(last) then
begin
Binary := '1' + Binary;
end
else
begin
Binary := '0' + Binary;
end;
Decimal := dividedByTwo(Decimal);
end;
// write a new line at the end
Writeln(OutFile, Binary);
until eof(InFile);
// close the file we are writing to
Close(OutFile);
end;
{ ----------------------------------------------------------- }
{ PROGRAM START }
begin
Main();
end.
{ ----------------------------------------------------------- }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment