0% found this document useful (0 votes)
6 views3 pages

ALU

Uploaded by

random help
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

ALU

Uploaded by

random help
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

2, ALU

module alu (
input wire [3:0] a, // 4-bit input A
input wire [3:0] b, // 4-bit input B
input wire [2:0] op, // 3-bit operation selector
output reg [3:0] result, // 4-bit result
output reg carry_out, // Carry out for addition/subtraction
output reg zero // Zero flag
);

// Operation codes
parameter ADD = 3'b000;
parameter SUB = 3'b001;
parameter AND = 3'b010;
parameter OR = 3'b011;
parameter XOR = 3'b100;
parameter NOT = 3'b101;

always @(*) begin


case (op)
ADD: begin
{carry_out, result} = a + b; // Perform addition with carry
end
SUB: begin
{carry_out, result} = a - b; // Perform subtraction with carry
end
AND: begin
result = a & b; // Perform bitwise AND
carry_out = 0;
end
OR: begin
result = a | b; // Perform bitwise OR
carry_out = 0;
end
XOR: begin
result = a ^ b; // Perform bitwise XOR
carry_out = 0;
end
NOT: begin
result = ~a; // Perform bitwise NOT on input A only
carry_out = 0;
end
default: begin
result = 4'b0000; // Default case
carry_out = 0;
end
endcase
zero = (result == 4'b0000); // Set zero flag if result is zero
end
endmodule

`timescale 1ns / 1ps


module tb_alu;

reg [3:0] a;
reg [3:0] b;
reg [2:0] op;
wire [3:0] result;
wire carry_out;
wire zero;

alu uut (
.a(a),
.b(b),
.op(op),
.result(result),
.carry_out(carry_out),
.zero(zero)
);

// Test sequence
initial begin
// Initialize signals
a = 4'd0;
b = 4'd0;
op = 3'b000;

// Test Case 1: Addition


#10 a = 4'd5; b = 4'd3; op = 3'b000; // a + b = 8
#10;

// Test Case 2: Subtraction


a = 4'd5; b = 4'd3; op = 3'b001; // a - b = 2
#10;

// Test Case 3: AND


a = 4'd7; b = 4'd3; op = 3'b010; // a & b = 3
#10;

// Test Case 4: OR
a = 4'd7; b = 4'd3; op = 3'b011; // a | b = 7
#10;

// Test Case 5: XOR


a = 4'd7; b = 4'd3; op = 3'b100; // a ^ b = 4
#10;

// Test Case 6: NOT


a = 4'd5; op = 3'b101; // ~a = -6 (in 4-bit 2's complement: 1010)
#10;
// Test Case 7: Invalid operation
a = 4'd0; b = 4'd0; op = 3'b111

You might also like