/projects/02/ALU.hdl
https://github.com/cpatuzzo/nand2tetris · Unknown · 79 lines · 67 code · 12 blank · 0 comment · 0 complexity · 2e9e564bef16f4bb99aa54d87e68505f MD5 · raw file
- // 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/02/ALU.hdl
-
- /**
- * The ALU. Computes one of the following functions:
- * x+y, x-y, y-x, 0, 1, -1, x, y, -x, -y, !x, !y,
- * x+1, y+1, x-1, y-1, x&y, x|y on two 16-bit inputs.
- * Which function to compute is determined by 6 input bits
- * denoted zx, nx, zy, ny, f, no.
- * The computed function's value is called "out".
- * In addition to computing out, the ALU computes two
- * 1-bit outputs called zr and ng:
- * if out == 0, zr = 1; otherwise zr = 0;
- * If out < 0, ng = 1; otherwise ng = 0.
- * The 6-bit combinations (zx,nx,zy,ny,f,no) and
- * their effect are documented in the book.
- */
-
- // Implementation: the ALU manipulates the x and y
- // inputs and then 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
- // if (out == 0) sets zr = 1
- // if (out < 0) sets ng = 1
-
-
- 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 (if f == 1) or out = x & y (if == 0)
- no; // negate the out output?
-
- OUT
- out[16], // 16-bit output
- zr, // 1 if (out == 0), 0 otherwise
- ng; // 1 if (out < 0), 0 otherwise
-
- PARTS:
- // zx
- Mux16(a=x, b=false, sel=zx, out=x1);
-
- // nx
- Not16(in=x1, out=notx1);
- Mux16(a=x1, b=notx1, sel=nx, out=x2);
-
- // zy
- Mux16(a=y, b=false, sel=zy, out=y1);
-
- // ny
- Not16(in=y1, out=noty1);
- Mux16(a=y1, b=noty1, sel=ny, out=y2);
-
- // f
- And16(a=x2, b=y2, out=and);
- Add16(a=x2, b=y2, out=add);
- Mux16(a=and, b=add, sel=f, out=func);
-
- // no, ng
- Not16(in=func, out=notfunc);
- Mux16(a=func, b=notfunc, sel=no, out=out, out[0..7]=lower, out[8..15]=upper, out[15]=ng);
-
- // zr
- Or8Way(in=lower, out=or1);
- Or8Way(in=upper, out=or2);
- Or(a=or1, b=or2, out=or);
- Not(in=or, out=zr);
- }