-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathALU.hdl
More file actions
63 lines (61 loc) · 2.28 KB
/
ALU.hdl
File metadata and controls
63 lines (61 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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:
//// Replace this comment with your code.
Mux16(a=x,b=false,sel=zx,out=nxo);
Not16(in=nxo,out=notx);
Mux16(a=nxo,b=notx,sel=nx,out=zxo);
Mux16(a=y,b=false,sel=zy,out=nyo);
Not16(in=nyo,out=noty);
Mux16(a=nyo,b=noty,sel=ny,out=zyo);
And16(a=zxo,b=zyo,out=xandy);
Add16(a=zxo,b=zyo,out=xaddy);
Mux16(a=xandy,b=xaddy,sel=f,out=fo);
Not16(in=fo,out=nfo);
Mux16(a=fo,b=nfo,sel=no,out=out);
Mux16(a=fo,b=nfo,sel=no,out[0..7]=out1,out[8..15]=out2);
Mux16(a=fo,b=nfo,sel=no,out[15]=outng,out[0..14]=outir);
Or8Way(in=out1,out=h1);
Or8Way(in=out2,out=h2);
Or(a=h1,b=h2,out=nzr);
Not(in=nzr,out=zr);
And(a=outng,b=true,out=ng);
}