Prev Problem
Next Problem

71. Arithmetic Logic Unit

module alu4 (
    input  [3:0] a,
    input  [3:0] b,
    input  [2:0] op,   // 000=ADD, 001=SUB, 010=AND, 011=OR, 100=XOR
    output reg [3:0] y,
    output reg       cf
);
    localparam [2:0]
        OP_ADD = 3'b000,
        OP_SUB = 3'b001,
        OP_AND = 3'b010,
        OP_OR  = 3'b011,
        OP_XOR = 3'b100;

    wire [4:0] add5 = {1'b0, a} + {1'b0, b};         // ADD path
    wire [4:0] sub5 = {1'b0, a} + {1'b0, ~b} + 5'b1; // SUB path

    always @* begin
        y  = 4'b0000;
        cf = 1'b0;
        case (op)
            OP_ADD: begin
                y  = add5[3:0];
                cf = add5[4];       // carry-out
            end
            OP_SUB: begin
                y  = sub5[3:0];
                cf = ~sub5[4];      // borrow = NOT carry-out
            end
            OP_AND: y = a & b;
            OP_OR : y = a | b;
            OP_XOR: y = a ^ b;
            default: begin y = 4'b0000; cf = 1'b0; end
        endcase
    end
endmodule

💡Remember

  • For unsigned subtraction using two’s complement, borrow-out = ~carry-out of a + (~b) + 1.
  • Keep results strictly 4-bit by taking [3:0]; capture carry/borrow with the 5th bit.
  • Logic ops don’t produce carry/borrow → set cf=0.