determine if int is power of 2

M

Moe Sisko

Using dotnet 2.0
I wrote some code to figure out if a number is a power of 2 :

==
private bool IsPowerOf2(int num)
{
int j = 0x1;
// test bits 0 .. 30. Don't use sign bit (bit 31).
for (int i = 0; i < 31; i++)
{
if (num == j)
return true;

j = j << 1;
}
return false;
}
==

It seems to work, but I got to wondering if there is a more efficient way to
do this. Any ideas ?

TIA
 
J

Jeroen Mostert

Moe said:
Using dotnet 2.0
I wrote some code to figure out if a number is a power of 2 :

==
private bool IsPowerOf2(int num)
{
int j = 0x1;
// test bits 0 .. 30. Don't use sign bit (bit 31).
for (int i = 0; i < 31; i++)
{
if (num == j)
return true;

j = j << 1;
}
return false;
}
==

It seems to work, but I got to wondering if there is a more efficient way to
do this. Any ideas ?
http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2

private bool IsPowerOf2(int num) {
return num > 0 && (num & (num - 1)) == 0;
}
 
M

Moe Sisko

MC said:
You could return false as soon as j > num. Is this a homework exercise?

Thanks. No, it's not a homework exercise (although granted, it probably
sounds like one said:
Why "int j = 0x1" instead of "int j = 1"?

No real reason - it just helps to remind myself that I'm doing bitwise
manipulation stuff.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top