Reputation: 458
I'm trying to solve this problem from altera Lab.
Here's my code :
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
I solved it assigning step by step the values in M, but I don't understand why this does not work:
M=(~S & X) | (S & Y);
Could someone explain why?
Upvotes: 2
Views: 598
Reputation: 6978
Note the bit widths of the signals in the expression
M=(~S & X) | (S & Y);
S
is only one bit while X
is 8 bits. The bitwise AND of the two will result in a one-bit result, which is not what you want.
It's common in Verilog to use a ternary expression in situations like this. For example,
assign M = S ? Y : X;
Upvotes: 3
Reputation: 62019
It does not work because S is a 1-bit signal and Y is an 8-bit signal. When you bitwise AND a 1-bit signal with an 8-bit signal, the 1-bit signal (S) is left extended with 0's.
For example, if S=1 and Y='hff, (S & Y) = (8'b0000_0001 & 8'b1111_1111) = 8'b0000_0001.
The same goes for (~S & X).
Using the replicated concatenation operator will work:
assign M = (~{8{S}} & X) | ({8{S}} & Y);
It is more conventional in Verilog to use the ternary operator to describe a mux:
assign M = (S) ? Y : X;
Upvotes: 3