10 if (num
>= res
+ bit
):
12 res
= (res
>> 1) + bit
20 //This is the main code of integer sqrt function found here:http://verilogcodes.blogspot.com/2017/11/a-verilog-function-for-finding-square-root.html
27 //Verilog function to find square root of a 32 bit number.
28 //The output is 16 bit.
30 input [31:0] num; //declare input
31 //intermediate signals.
34 reg [17:0] left,right,r;
37 //initialize all the variables.
41 left = 0; //input to adder/sub
42 right = 0; //input to adder/sub
44 //run the calculations for 16 iterations.
45 for(i=0;i<16;i=i+1) begin
46 right = {q,r[17],1'b1};
47 left = {r[15:0],a[31:30]};
48 a = {a[29:0],2'b00}; //left shift by 2 bits.
49 if (r[17] == 1) //add if r is negative
51 else //subtract if r is positive
55 sqrt = q; //final assignment of output.
57 endfunction //end of Function
60 c version (from paper linked from URL)
62 unsigned squart(D, r) /*Non-Restoring sqrt*/
63 unsigned D; /*D:32-bit unsigned integer to be square rooted */
66 unsigned Q = 0; /*Q:16-bit unsigned integer (root)*/
67 int R = 0; /*R:17-bit integer (remainder)*/
69 for (i = 15;i>=0;i--) /*for each root bit*/
73 R = R<<2)|((D>>(i+i))&3);
74 R = R-((Q<<2)|1); /*-Q01*/
78 R = R<<2)|((D>>(i+i))&3);
79 R = R+((Q<<2)|3); /*+Q11*/
81 if (R>=0) Q = Q<<1)|1; /*new Q:*/
82 else Q = Q<<1)|0; /*new Q:*/
85 /*remainder adjusting*/
86 if (R<0) R = R+((Q<<1)|1);
87 *r = R; /*return remainder*/
88 return(Q); /*return root*/
93 short isqrt(short num) {
95 short bit = 1 << 14; // The second-to-top bit is set: 1 << 30 for 32 bits
97 // "bit" starts at the highest power of four <= the argument.
102 if (num >= res + bit) {
104 res = (res >> 1) + bit;