Verilog-2001 Code Book  return  signal-process-logic.com
// followings are sample codes of "Verilog-2001 Code Book"
// Test for "Cyclone III EP3C25F324C6"

module add_sub(
	input [15:0] ina_p, inb_p,
	output reg [31:0] result_p,
	output reg error_p,
	input clock);
	
	reg [15:0] ina, inb;
	wire [31:0] result;
	wire error;
	
	always @(posedge clock) begin
		ina <= ina_p;
		inb <= inb_p;
		result_p <= result;
		error_p <= error;
	end
// test module difinition: erase only 1 comment of following lines	
//	unsigned_add u1 (.ina(ina), .inb(inb), .result(result[16:0])); 
//		assign {error, result[31:17]} = 16'h0;
//	unsigned_add_clip u1 (.ina(ina), .inb(inb), .result(result[15:0]),
//		.error(error)); assign result[31:16] = 16'h0;
//	unsigned_sub_clip u1 (.ina(ina), .inb(inb), .result(result[15:0]),
//		.error(error)); assign result[31:16] = 16'h0;
//	signed_add u1 (.ina(ina), .inb(inb), .result(result[16:0]));
//		assign {error, result[31:17]} = 16'h0;
//	signed_add_check_alt u1 (.ina(ina), .inb(inb), .result(result[15:0]),
//		.overflow(error)); assign result[31:16] = 16'h0;
//	signed_add_check u1 (.ina(ina), .inb(inb), .result(result[15:0]),
//		.overflow(error)); assign result[31:16] = 16'h0;
	signed_clip u1 (.in({ina, inb}), .result(result[15:0]),
		.error(error)); assign result[31:16] = 16'h0;

endmodule
// 1.1
module unsigned_add(		// _1
	input [15:0] ina, inb,
	output [16:0] result);
	
	assign result = ina + inb;
endmodule

module unsigned_add_clip(		// _2
	input [15:0] ina, inb,
	output [15:0] result,
	output error);
	
	wire [16:0] work = ina + inb;
	assign result = work[16] ? {16{1'b1}} : work[15:0];
	assign error = work[16];
endmodule

module unsigned_sub_clip(		// _3
	input [15:0] ina, inb,
	output [15:0] result,
	output error);
	
	wire [16:0] work = ina - inb;
	assign result = work[16] ? {16{1'b0}} : work[15:0];
	assign error = work[16];
endmodule

// 1.2
module signed_add(			// _4
	input [15:0] ina, inb,
	output [16:0] result);
	
	assign result = {ina[15], ina} + {inb[15], inb};
endmodule

module signed_sub(			
	input [15:0] ina, inb,
	output [16:0] result);
	
	assign result = {ina[15], ina} - {inb[15], inb};
endmodule

module signed_add_check_alt(	// _5
	input [15:0] ina, inb,
	output [15:0] result,
	output overflow);
	
	assign result = ina + inb;
	assign overflow = ~(ina[15] ^ inb[15]) &
		(ina[15] ^ result[15]);
endmodule

module signed_add_check(		// _6
	input [15:0] ina, inb,
	output [15:0] result,
	output overflow);
	
	wire [16:0] work = {ina[15], ina} + {inb[15], inb};
	assign result = work[15:0];
	assign overflow = ^work[16:15];
endmodule

module signed_clip(				// _7
	input [31:0] in,
	output [15:0] result,
	output error);
	
	assign error = ~&in[31:15] & |in[31:15];
	assign result = ~error ? in[15:0] :
		(in[31] ? 32'h8000 : 32'h7FFF); 
endmodule
 Verilog-2001 Code Book  return  signal-process-logic.com