From 23e3ab77fbfd42c277671ade0f13d8f7989f7ea3 Mon Sep 17 00:00:00 2001 From: icmor Date: Wed, 15 May 2024 20:11:02 -0600 Subject: [PATCH] Arithmetic Logic Unit --- combinationalChips/ALU.hdl | 63 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 combinationalChips/ALU.hdl diff --git a/combinationalChips/ALU.hdl b/combinationalChips/ALU.hdl new file mode 100644 index 0000000..f85c8c4 --- /dev/null +++ b/combinationalChips/ALU.hdl @@ -0,0 +1,63 @@ +// This file is part of www.nand2tetris.org +// and the book "The Elements of Computing Systems" +// by Nisan and Schocken, MIT Press. +// File name: projects/2/ALU.hdl +/** + * ALU (Arithmetic Logic Unit): + * Computes out = one of the following functions: + * 0, 1, -1, + * x, y, !x, !y, -x, -y, + * x + 1, y + 1, x - 1, y - 1, + * x + y, x - y, y - x, + * x & y, x | y + * on the 16-bit inputs x, y, + * according to the input bits zx, nx, zy, ny, f, no. + * In addition, computes the two output bits: + * if (out == 0) zr = 1, else zr = 0 + * if (out < 0) ng = 1, else ng = 0 + */ +// Implementation: Manipulates the x and y inputs +// and operates on the resulting values, as follows: +// if (zx == 1) sets x = 0 // 16-bit constant +// if (nx == 1) sets x = !x // bitwise not +// if (zy == 1) sets y = 0 // 16-bit constant +// if (ny == 1) sets y = !y // bitwise not +// if (f == 1) sets out = x + y // integer 2's complement addition +// if (f == 0) sets out = x & y // bitwise and +// if (no == 1) sets out = !out // bitwise not + +CHIP ALU { + IN + x[16], y[16], // 16-bit inputs + zx, // zero the x input? + nx, // negate the x input? + zy, // zero the y input? + ny, // negate the y input? + f, // compute (out = x + y) or (out = x & y)? + no; // negate the out output? + OUT + out[16], // 16-bit output + zr, // if (out == 0) equals 1, else 0 + ng; // if (out < 0) equals 1, else 0 + + PARTS: + Mux16(a=x, b=false, sel=zx, out=x0); // x = 0 + Not16(in=x0, out=notx); // x != x + Mux16(a=x0, b=notx, sel=nx, out=x1); + Mux16(a=y, b=false, sel=zy, out=y0); // y = 0 + Not16(in=y0, out=noty); // y != y + Mux16(a=y0, b=noty, sel=ny, out=y1); + Add16(a=x1, b=y1, out=sum); // x + y + And16(a=x1, b=y1, out=and); // x & y + Mux16(a=and, b=sum, sel=f, out=result); // f + Not16(in=result, out=notresult); // !out + + // Outputs + Mux16(a=result, b=notresult, sel=no, + out=out, out[0..7]=lo8, + out[8..15]=hi8, out[15]=ng); + Or8Way(in=lo8, out=lozr); // zr + Or8Way(in=hi8, out=hizr); + Or(a=lozr, b=hizr, out=zr0); + Not(in=zr0, out=zr); +}