12 if (num
>= res
+ bit
):
14 res
= (res
>> 1) + bit
23 //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
30 //Verilog function to find square root of a 32 bit number.
31 //The output is 16 bit.
33 input [31:0] num; //declare input
34 //intermediate signals.
37 reg [17:0] left,right,r;
40 //initialize all the variables.
44 left = 0; //input to adder/sub
45 right = 0; //input to adder/sub
47 //run the calculations for 16 iterations.
48 for(i=0;i<16;i=i+1) begin
49 right = {q,r[17],1'b1};
50 left = {r[15:0],a[31:30]};
51 a = {a[29:0],2'b00}; //left shift by 2 bits.
52 if (r[17] == 1) //add if r is negative
54 else //subtract if r is positive
58 sqrt = q; //final assignment of output.
60 endfunction //end of Function
63 c version (from paper linked from URL)
65 unsigned squart(D, r) /*Non-Restoring sqrt*/
66 unsigned D; /*D:32-bit unsigned integer to be square rooted */
69 unsigned Q = 0; /*Q:16-bit unsigned integer (root)*/
70 int R = 0; /*R:17-bit integer (remainder)*/
72 for (i = 15;i>=0;i--) /*for each root bit*/
76 R = R<<2)|((D>>(i+i))&3);
77 R = R-((Q<<2)|1); /*-Q01*/
81 R = R<<2)|((D>>(i+i))&3);
82 R = R+((Q<<2)|3); /*+Q11*/
84 if (R>=0) Q = Q<<1)|1; /*new Q:*/
85 else Q = Q<<1)|0; /*new Q:*/
88 /*remainder adjusting*/
89 if (R<0) R = R+((Q<<1)|1);
90 *r = R; /*return remainder*/
91 return(Q); /*return root*/
96 short isqrt(short num) {
98 short bit = 1 << 14; // The second-to-top bit is set: 1 << 30 for 32 bits
100 // "bit" starts at the highest power of four <= the argument.
105 if (num >= res + bit) {
107 res = (res >> 1) + bit;