# verilog code to find max and min in an input signal..

**URL:** <https://forum.kirupa.com/t/verilog-code-to-find-max-and-min-in-an-input-signal/634659>\
**Category:** Uncategorized\
**Created:** [May 22, 2016, 4:37am UTC](https://forum.kirupa.com/t/verilog-code-to-find-max-and-min-in-an-input-signal/634659 "2016-05-22T04:37:27Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![MR.sam](https://avatars.discourse-cdn.com/v4/letter/m/b5e925/32.png) [@MR.sam](https://forum.kirupa.com/u/MR.sam)\
**Post date:** [May 22, 2016, 4:37am UTC](https://forum.kirupa.com/t/verilog-code-to-find-max-and-min-in-an-input-signal/634659/1 "2016-05-22T04:37:27Z")

</div>

I want to find max and min in input file, read from a memory. This input file containsize 1000 decimal sample values. I have written the following code to find max and min by comparing with a threshold.

module max\_min(input clk, input [15:0]din, output [15:0]dout);  
reg [15:0]max=0;  
reg [15:0]min=0;  
always @(posedge clk) begin  
if($signed(din)\>max)  
max=din;  
else if($signed(din)\<min)  
min=din;  
end  
assign dout=max;`  
endmodule  
The problem in above code is that for example the if condition becomes true for (eg) the 2nd cycle sample value, then max will be assigned the 2nd sample value as max sample value. Now let us consider that input din has max sample value at the 15th cycle of all the 1000 samples. So after the 15th cycle max will contain that max value and the output dout will contain max value after 15th cycle and before 15th cycle it will contain the maximum of the first 14 sample values. I want my output i.e max register to contain only the maximum value i.e the 15th value.

verilog system-verilog
