# Square Root Of An Unsigned Long

## Recommended Posts

Unfortunately Boost C math library doesn't support the square root function for a data type greater than unsigned int. I'm looking for some suggestions or code examples on how to accomplish the square root of an unsigned long. Currently working on a project where the customer has requested code enhancements that calculate standard deviation of 12-bit ADC sensor readings. The averaged sum of squares value can be quite large hence the unsigned long data type. Any help would be appreciated.

thx

Sparky

##### Share on other sites

Hi Sparky,

This appears to be the standard method irrespective of data size (32, 16 0r 8).

A quick Google search found it, and seems to work in SB.

```#include <system.h>
typedef unsigned long uint32_t;
uint32_t isqrt32 (uint32_t n)
{
uint32_t root, remainder, place;
root = 0;
remainder = n;
place = 0x40000000;
while (place > remainder)
place = place >> 2;
while (place)
{
if (remainder >= root + place)
{
remainder = remainder - root - place;
root = root + (place << 1);
}
root = root >> 1;
place = place >> 2;
}
return root;
}
void main()
{
uint32_t result;

result = isqrt32(1234567890);
}

```

Cheers

Reynard

##### Share on other sites

Thanks Reynard.

I went with this and it seems to work correctly and is very fast. However I may revert to the example you provided for the long term since it's more flexible for different data types.

```unsigned int sqrt32 (unsigned long n)
{
unsigned long c = 0x8000;
unsigned long g = 0x8000;
for(;
{
if(g * g > n)
g ^= c;
c >>= 1;
if(c == 0)
return g;
g |= c;
}
}
```

## Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.