Nand2Tetris: How to code 16-bit constant in ALU

412 Views Asked by At

I'm doing ALU task in Project 2 in Nand2Tetris course.

// and operates on the resulting values, as follows:
// if (zx == 1) set x = 0        // 16-bit constant
// if (nx == 1) set x = !x       // bitwise not
// if (zy == 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

I'm trying to do the first one - if zx == 1, then x = 0.

Or (a=zx, b=x[0..15], out=zerox[0..15]);
Not (in=zeroY[0..15], out=out[0..15]);

The logic is that if zx is 1, then Or will produce 1, and by negating it I'll get 0 which is I'm expected to do. The problem is that zx is a1-bit input, but x[0..15], and output are 16-bit values. I have been thinking over the problem several days, and still can't figure out how I can overcome it. I'm not even sure that Or is correct or efficient here, maybe something like Mux would be better. But in that case too, I don't know how I can avoid mixing 1-bit and 16-bit inputs?

Any help / hint is appreciated.

1

There are 1 best solutions below

3
MadOverlord On

There are HDL constants "true" and "false", which you can use as inputs to logical units, and which are automatically sized, so if the input requirement is a 16 bit bus, you get 16 bits of the appropriate value. See Appendix 2.2 in the book for more details.

Another thing that this Appendix explains is that the output of a component can be sliced and diced and output in multiple ways simultaneously. Consider the Mux16 component for example:

Mux16(a=x,b=y,sel=choose,out=result);

You don't have to just settle for a single 16-bit output bus (result in this case). You can do stuff like:

Mux16(a=x,b=y,sel=choose,out=result16,out[0]=lobit,out[4..7]=secondnybble);

You can do similar things with inputs, for example, extracting a subset of a wider bus and welding together smaller buses into a wider input.

Finally, bits in an input or output bus that are not specified are set to zero (as long as some of the other bits are being set to something).

Enjoy the course! It's a ton of fun.