Skip to content
code0.HDL

32Implementation

Select a bitwise operation

Problem

selectOp is a pure function. It computes a 4-bit result from two 4-bit operands a and b, and a 2-bit selector sel decides which bitwise operation is applied:

selResult
0a & b (AND)
1a | b (OR)
2a ^ b (XOR)
3~(a | b) (NOR)

All four selector values are defined; there is no unused case. The starter returns ?, so its output is chosen by the compiler rather than defined by the required operation table.

Edit only the body of selectOp at the TODO. Keep its signature and mkTop unchanged.

Read and predict

mkTop calls selectOp with a = 1100 and b = 1010 once per selector value, then once more with both operands zero and sel = 3. Before running, write the five expected results by hand: AND keeps the bits set in both operands, OR keeps the bits set in either, XOR keeps the bits that differ, and NOR sets exactly the bits that OR clears. Run the unchanged starter once and compare each line with the prediction. An accidental match does not show that the operation was implemented.

Implementation path

Express the choice as a selection on sel with one arm per selector value, and compute every arm from both operands. Run again. The four lines for 1100 and 1010 should read 1000, 1110, 0110, and 0001, and the all-zero NOR should read 1111.

A function has no clock and no state, so the result follows from the arguments alone. The same rule must hold for operand pairs the public run never prints.

Completion contract

  • Each selector value from 0 to 3 applies its operation to all 256 operand pairs, not only to the two operands mkTop prints.
  • NOR is the complement of OR: a result bit is 1 exactly where both operand bits are 0.
  • The result width stays Bit#(4) and the signature is unchanged.
  • No selector value returns an undefined or don't-care result.

Progressive hints

Hint 1

? leaves the value to the compiler. The function must choose between four expressions, and the one input that changes the choice is sel, not a or b.

Hint 2

A case on sel, or a chain of conditional operators, covers the four selector values. Each arm applies one bitwise operator from the chapter's operator table to a and b.

Hint 3

There is no single NOR operator. Build it from the complement ~ of the OR of both operands, and keep the parentheses so the complement applies to the whole OR rather than to a alone.

Transfer experiment

After the required version works, change the operands in mkTop to a = 4'b0101 and b = 4'b0101. Predict all four results first: for equal operands AND and OR agree and NOR is their complement, while XOR becomes zero. Restore the original operands before submitting.

Review this concept
Ready
Main.bsv