// 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 (Arithmetic Logic Unit). * 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, * according to 6 input bits denoted notZX,nx,notZY,ny,f,no. * In addition, the ALU computes two 1-bit outputs: * if the ALU output == 0, zr is set to 1; otherwise zr is set to 0; * if the ALU output < 0, ng is set to 1; otherwise ng is set to 0. */ // Implementation: the ALU logic manipulates the x and y inputs // and operates on the resulting values, as follows: // if (notZX == 1) set x = 0 // 16-bit constant // if (nx == 1) set x = !x // bitwise not // if (notZY == 1) set y = 0 // 16-bit constant // if (ny == 1) set y = !y // bitwise not // if (f == 1) set out = x + y // integer 2's complement addition // if (f == 0) set out = x & y // bitwise and // if (no == 1) set out = !out // bitwise not // if (out == 0) set zr = 1 // if (out < 0) set 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 1) or 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: // Put you code here: Not(in=zx,out=notZX); Not(in=zy,out=notZY); And16(a[0]=notZX,a[1]=notZX,a[2]=notZX,a[3]=notZX,a[4]=notZX,a[5]=notZX,a[6]=notZX,a[7]=notZX,a[8]=notZX,a[9]=notZX,a[10]=notZX,a[11]=notZX,a[12]=notZX,a[13]=notZX,a[14]=notZX,a[15]=notZX,b=x,out=ZX); And16(a[0]=notZY,a[1]=notZY,a[2]=notZY,a[3]=notZY,a[4]=notZY,a[5]=notZY,a[6]=notZY,a[7]=notZY,a[8]=notZY,a[9]=notZY,a[10]=notZY,a[11]=notZY,a[12]=notZY,a[13]=notZY,a[14]=notZY,a[15]=notZY,b=y,out=ZY); Xor16(a[0]=nx,a[1]=nx,a[2]=nx,a[3]=nx,a[4]=nx,a[5]=nx,a[6]=nx,a[7]=nx,a[8]=nx,a[9]=nx,a[10]=nx,a[11]=nx,a[12]=nx,a[13]=nx,a[14]=nx,a[15]=nx,b=ZX,out=NX); Xor16(a[0]=ny,a[1]=ny,a[2]=ny,a[3]=ny,a[4]=ny,a[5]=ny,a[6]=ny,a[7]=ny,a[8]=ny,a[9]=ny,a[10]=ny,a[11]=ny,a[12]=ny,a[13]=ny,a[14]=ny,a[15]=ny,b=ZY,out=NY); Add16(a=NX,b=NY,out=sumout); And16(a=NX,b=NY,out=andout); Not(in=f,out=notF); And16(a[0]=f,a[1]=f,a[2]=f,a[3]=f,a[4]=f,a[5]=f,a[6]=f,a[7]=f,a[8]=f,a[9]=f,a[10]=f,a[11]=f,a[12]=f,a[13]=f,a[14]=f,a[15]=f,b=sumout,out=out1); And16(a[0]=notF,a[1]=notF,a[2]=notF,a[3]=notF,a[4]=notF,a[5]=notF,a[6]=notF,a[7]=notF,a[8]=notF,a[9]=notF,a[10]=notF,a[11]=notF,a[12]=notF,a[13]=notF,a[14]=notF,a[15]=notF,b=andout,out=out2); Xor16(a=out1,b=out2,out=out3); Xor16(a[0]=no,a[1]=no,a[2]=no,a[3]=no,a[4]=no,a[5]=no,a[6]=no,a[7]=no,a[8]=no,a[9]=no,a[10]=no,a[11]=no,a[12]=no,a[13]=no,a[14]=no,a[15]=no,b=out3,out=output); And16(a=output,b=output,out=out); Not16(in=output,out=notOut); Add16Way(in=notOut,out=zr); CheckPin16(in=output,out=ng); }