Wrote a code snippet to see if an unsigned integer is a valid mask.If anyone has a more efficient algorithm I like to know ...bool CheckValidMask(unsigned int x){bool validmask = true;unsigned int shift, oldshift;shift = 0;unsigned int num = x;while ((x > 0) && (validmask == true)){ oldshift = shift; shift = x - (x&(x-1)); if ((shift>>1 != oldshift)&&(oldshift !=0)) { validmask = false; } x = x&(x-1);}return validmask;}
the only response I got was/* unsigned uint32_t x */return !(x & (~x>>1));a lot more compact than what I wrote
Post a Comment
2 comments:
Wrote a code snippet to see if an unsigned integer is a valid mask.
If anyone has a more efficient algorithm I like to know ...
bool CheckValidMask(unsigned int x)
{
bool validmask = true;
unsigned int shift, oldshift;
shift = 0;
unsigned int num = x;
while ((x > 0) && (validmask == true))
{
oldshift = shift;
shift = x - (x&(x-1));
if ((shift>>1 != oldshift)&&(oldshift !=0))
{
validmask = false;
}
x = x&(x-1);
}
return validmask;
}
the only response I got was
/* unsigned uint32_t x */
return !(x & (~x>>1));
a lot more compact than what I wrote
Post a Comment