为什么这个verilog分配是错误的?

Why this verilog assignment is wrong?

我正在尝试从 altera Lab 解决这个问题。

这是我的代码:

module AlteraLAB2
(
    input [17:0] SW,
    output [17:0] LEDR,
    output [7:0] LEDG
);
wire S;
wire [7:0] X,Y,M;

//Use switch SW17 on the DE2 board as the s input, switches SW7−0 as the X input and SW15−8 as the Y input
assign S = SW[17];
assign X = SW[7:0];
assign Y = SW[15:8];

//Connect the SW switches to the red lights LEDR and connect the output M to the green lights LEDG7−0
assign LEDR = SW[17:0];
assign LEDG = M;


//The multiplexer can be described by the following Verilog statement: assign m=(~s & x)|(s & y); 
assign M[0] = (~S & X[0]) | (S & Y[0]);
assign M[1] = (~S & X[1]) | (S & Y[1]);
assign M[2] = (~S & X[2]) | (S & Y[2]);
assign M[3] = (~S & X[3]) | (S & Y[3]);
assign M[4] = (~S & X[4]) | (S & Y[4]);
assign M[5] = (~S & X[5]) | (S & Y[5]);
assign M[6] = (~S & X[6]) | (S & Y[6]);
assign M[7] = (~S & X[7]) | (S & Y[7]);
endmodule

我解决了逐步分配 M 中的值的问题,但我不明白为什么这不起作用:

M=(~S & X) | (S & Y);

有人可以解释为什么吗?

它不起作用,因为S是1位信号,Y是8位信号。当您按位将 1 位信号与 8 位信号进行 AND 运算时,1 位信号 (S) 将用 0 进行扩展。

例如,如果 S=1 且 Y='hff,则 (S & Y) = (8'b0000_0001 & 8'b1111_1111) = 8'b0000_0001。

同样适用于 (~S & X)。

使用复制的串联运算符将起作用:

assign M = (~{8{S}} & X) | ({8{S}} & Y);

在Verilog中使用三元运算符来描述多路复用器是更传统的做法:

assign M = (S) ? Y : X;

注意表达式中信号的位宽

M=(~S & X) | (S & Y);

S只有一位,而X是8位。两者按位与会得到一位结果,这不是你想要的。

在 Verilog 中,在这种情况下使用三元表达式很常见。例如,

assign M = S ? Y : X;