Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return if a given int is an exponent of 2 C#

Tags:

c#

Given a method of the bool data type that takes in an int variable, what is a single line of code that would determine if the int is an exponent of 2 or 2^n.....2,4,8,16,32 etc. I know of a way using a while loop and if statements, but I'm looking for it to be on one line.

like image 767
Nard Dog Avatar asked Dec 02 '25 08:12

Nard Dog


1 Answers

From Bit Twiddling Hacks:

uint v;         // we want to see if v is a power of 2
bool f;         // the result goes here 

f = (v != 0) && ((v & (v - 1)) == 0);
like image 134
dtb Avatar answered Dec 03 '25 23:12

dtb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!