4 //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
11 //Verilog function to find square root of a 32 bit number.
12 //The output is 16 bit.
14 input [31:0] num; //declare input
15 //intermediate signals.
18 reg [17:0] left,right,r;
21 //initialize all the variables.
25 left = 0; //input to adder/sub
26 right = 0; //input to adder/sub
28 //run the calculations for 16 iterations.
29 for(i=0;i<16;i=i+1) begin
30 right = {q,r[17],1'b1};
31 left = {r[15:0],a[31:30]};
32 a = {a[29:0],2'b00}; //left shift by 2 bits.
33 if (r[17] == 1) //add if r is negative
35 else //subtract if r is positive
39 sqrt = q; //final assignment of output.
41 endfunction //end of Function
44 c version (from paper linked from URL)
46 unsigned squart(D, r) /*Non-Restoring sqrt*/
47 unsigned D; /*D:32-bit unsigned integer to be square rooted */
50 unsigned Q = 0; /*Q:16-bit unsigned integer (root)*/
51 int R = 0; /*R:17-bit integer (remainder)*/
53 for (i = 15;i>=0;i--) /*for each root bit*/
57 R = R<<2)|((D>>(i+i))&3);
58 R = R-((Q<<2)|1); /*-Q01*/
62 R = R<<2)|((D>>(i+i))&3);
63 R = R+((Q<<2)|3); /*+Q11*/
65 if (R>=0) Q = Q<<1)|1; /*new Q:*/
66 else Q = Q<<1)|0; /*new Q:*/
69 /*remainder adjusting*/
70 if (R<0) R = R+((Q<<1)|1);
71 *r = R; /*return remainder*/
72 return(Q); /*return root*/
77 short isqrt(short num) {
79 short bit = 1 << 14; // The second-to-top bit is set: 1 << 30 for 32 bits
81 // "bit" starts at the highest power of four <= the argument.
86 if (num >= res + bit) {
88 res = (res >> 1) + bit;