58 lines
1.2 KiB
Plaintext
58 lines
1.2 KiB
Plaintext
MODULE GrayCode;
|
|
|
|
FROM STextIO IMPORT
|
|
WriteString, WriteLn;
|
|
FROM SWholeIO IMPORT
|
|
WriteInt;
|
|
FROM Conversions IMPORT
|
|
LongBaseToStr;
|
|
FROM FormatString IMPORT
|
|
FormatString; (* for justifying *)
|
|
|
|
VAR
|
|
I, G, D: CARDINAL;
|
|
Ok: BOOLEAN;
|
|
BinS, OutBinS: ARRAY[0 .. 5] OF CHAR;
|
|
|
|
PROCEDURE Encode(V: CARDINAL): CARDINAL;
|
|
BEGIN
|
|
RETURN V BXOR (V SHR 1)
|
|
END Encode;
|
|
|
|
PROCEDURE Decode(V: CARDINAL): CARDINAL;
|
|
VAR
|
|
Result: CARDINAL;
|
|
BEGIN
|
|
Result := 0;
|
|
WHILE V > 0 DO
|
|
Result := Result BXOR V;
|
|
V := V SHR 1
|
|
END;
|
|
RETURN Result
|
|
END Decode;
|
|
|
|
BEGIN
|
|
WriteString("decimal binary gray decoded");
|
|
WriteLn;
|
|
FOR I := 0 TO 31 DO
|
|
G := Encode(I);
|
|
D := Decode(G);
|
|
WriteInt(I, 4);
|
|
WriteString(" ");
|
|
Ok := LongBaseToStr(I, 2, BinS);
|
|
Ok := FormatString("%'05s", OutBinS, BinS);
|
|
(* Padded with 0; width: 5; type: string *)
|
|
WriteString(OutBinS);
|
|
WriteString(" ");
|
|
Ok := LongBaseToStr(G, 2, BinS);
|
|
Ok := FormatString("%'05s", OutBinS, BinS);
|
|
WriteString(OutBinS);
|
|
WriteString(" ");
|
|
Ok := LongBaseToStr(D, 2, BinS);
|
|
Ok := FormatString("%'05s", OutBinS, BinS);
|
|
WriteString(OutBinS);
|
|
WriteInt(D, 4);
|
|
WriteLn;
|
|
END
|
|
END GrayCode.
|