代码之家  ›  专栏  ›  技术社区  ›  user243557

Nand2Tetris:如何在ALU中编码16位常量

  •  0
  • user243557  · 技术社区  · 1 年前

    我在Nand2Tetris课程的项目2中做ALU任务。

    // 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
    

    我试着做第一个——如果zx==1,那么x=0。

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

    逻辑是,如果zx是1,那么Or将产生1,通过否定它,我将得到0,这是我应该做的。 问题是zx是a1位输入,但x[0..15],并且输出是16位值。我已经思考了好几天了,仍然不知道如何克服它。我甚至不确定Or在这里是正确的还是有效的,也许像Mux这样的东西会更好。但在这种情况下,我也不知道如何避免混合1位和16位输入?

    如有任何帮助/提示,我们将不胜感激。

    0 回复  |  直到 1 年前
        1
  •  1
  •   Trebor the MadOverlord    1 年前

    有HDL常量“true”和“false”,您可以将它们用作逻辑单元的输入,并自动调整大小,因此如果输入要求是16位总线,则可以获得适当值的16位。详见本书附录2.2。

    本附录解释的另一件事是,组件的输出可以切片和切块,并以多种方式同时输出。以Mux16组件为例:

    Mux16(a=x,b=y,sel=选择,out=结果);

    您不必只满足于单个16位输出总线(在本例中为结果)。你可以做以下事情:

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

    您可以对输入执行类似的操作,例如,提取更宽总线的子集,并将较小的总线焊接到更宽的输入中。

    最后,输入或输出总线中未指定的位被设置为零(只要其他一些位被设置成某个值)。

    享受课程吧!这很有趣。