Hello everyone once again,
I need to write a code in Pascal which converts a decimal number into a binary number, and saves this into an array, and then writes it from MSD to LSD.
I've got most of the code, however when I want to print it, I don't understand one significant thing:
I put the codesnippet
FOR i := 15 DOWNTO 1 DO
write(Integer(dualCalc[i]));
as output. When I run this program, I get the number 0000000000001010 as output, which is correct and also 16 bits. How? 15 DOWNTO 1 is only 15 bits, so how is the output 16 bits?
When I put
FOR i := 15 DOWNTO 0 DO
write(Integer(dualCalc[i]));
I get 00000000000010100, which is just wrong and 17 bits.
Can someone explain to me how this is possible?
Entire Code below.
PROGRAM ConvertNum;
TYPE
dual = ARRAY[0..15] OF BOOLEAN;
PROCEDURE Dec2Dual (decimal: INTEGER; VAR dualCalc: dual);
VAR
i: INTEGER;
calculation: INTEGER;
divisionBool: BOOLEAN;
BEGIN
i := 0;
WHILE (i < 16) AND (decimal > 0) DO
BEGIN
calculation := decimal mod 2;
IF calculation = 0 THEN
divisionBool := FALSE
ELSE
divisionBool := TRUE;
dualCalc[i] := divisionBool;
decimal := decimal div 2;
i := i + 1;
END;
FOR i := 15 DOWNTO 0 DO
write(Integer(dualCalc[i]));
END;
VAR
aThree: ARRAY[0..15] OF BOOLEAN;
inputVar: INTEGER;
DecOut: INTEGER;
BEGIN
readln(inputVar);
Dec2Dual(inputVar, aThree);
END.
for
‑loop limits are inclusive.
Thus a loop
for x := 1 to 1 do
begin
writeLn(x)
end
prints one line containing 1
.
This circumstance is probably inspired by mathematicians’ notation of sums and products, ∑ and ∏, that uses inclusive limits, too.