Skip to content
code0.HDL

03Implementation

Select one of four operations

1. Required behaviour

select_op is a combinational block with no clock. A 2-bit input sel chooses an operation, which is applied to the two 4-bit inputs a and b; the result appears on the 4-bit output y. When an input changes, y follows without waiting for any edge.

sely
0a & b
1a | b
2a ^ b
3~(a | b)

Each operation works bit by bit: with a = 1100, b = 1010 and sel = 2, y = 0110. All four select values must be defined. No finished code is given: the starter has the port list and a case skeleton that gives y 0 in every case, and filling that skeleton with the four operations is the task. Keep the ports and the public testbench below the marker as they are.

2. Reading the public testbench

The testbench holds a = 1100, b = 1010 and steps sel from 0 to 3, printing one line each, then repeats with a = b = 0101. There is no clock. It changes the inputs, waits #1, and prints y, so every line is the combinational output for that input.

Before editing, write the eight y values from the table. For the equal inputs 0101, 0101, XOR gives 0000 and NOR gives 1010.

3. Completion conditions

  • For all 1,024 combinations of sel, a and b, y matches the table.
  • Moving from any combination to any other, y is decided by the new inputs alone. A storage element that keeps the value of the previous combination does not satisfy this.
  • With a and b fixed, changing only sel selects the corresponding operation; different operations can produce the same y for those inputs.

4. Hints, in order

Hint 1

Inside always @*, branch on the value of sel. One branching statement can list all four cases; see the procedural assignment section of the Basic syntax chapter.

Hint 2

If any of the four cases leaves y unassigned, y keeps its previous value in that case, which is a latch. Assign y in every case, or make the last case default.

Hint 3

NOR is OR inverted. ~ inverts bit by bit, so the OR has to be in parentheses, ~(a | b), for its result to be inverted.

5. Further experiment

Write the same behaviour with assign and the conditional operator ? : instead of the always @* block; output reg then becomes output. Grading compares behaviour only, so both forms pass. For an 8-bit variant, first write down which declarations change, then predict how the public testbench's lines would differ.

Review this concept
Ready
Main.v