Sure, here’s an example of a 4-bit ALU implemented using SystemVerilog:
module alu_4bit( input logic [3:0] a, input logic [3:0] b, input logic [2:0] op, output logic [3:0] out ); always_comb begin case(op) 3'b000: out = a + b; // add 3'b001: out = a - b; // subtract 3'b010: out = a & b; // bitwise AND 3'b011: out = a | b; // bitwise OR 3'b100: out = a ^ b; // bitwise XOR 3'b101: out =
a; // bitwise NOT of a
3’b110: out =
b; // bitwise NOT of b 3'b111: out = 4'b0; // clear output default: out = 4'b0; // clear output for undefined op endcase end endmodule
In this code, we define a module called `alu_4bit` with three input ports `a`, `b`, and `op`, and an output port `out`. The `a` and `b` inputs are 4-bit binary values, and the `op` input is a 3-bit binary value that represents the operation to be performed. The `out` output is a 4-bit binary value that represents the result of the operation.
The `always_comb` block is used to describe the behavior of the ALU. The `case` statement is used to select the appropriate operation based on the value of the `op` input signal.
For example, if the `op` signal is `3’b010`, the output signal `out` will be the result of the bitwise AND operation between `a` and `b`.
In addition to basic arithmetic and logic operations, the ALU also supports bitwise NOT of `a` and `b`, as well as clearing the output signal. If an undefined operation code is selected, the output signal is cleared.
You can instantiate this module in your top-level design hierarchy and connect it to other modules or input/output signals as needed. Note that you can modify the code to implement a wider or narrower ALU by changing the bit width of the input and output signals.