Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Give a one-line C expression to test whether a number is a power of 2. [No loops allowed]?
Posted
Comments
JackDingler 7-Sep-12 13:27pm    
Hope you get an A on your homework.
Chuck O'Toole 7-Sep-12 16:16pm    
Amazing coincidence, the link in solution 2 below is to a question that is worded exactly the same but posted in November of 2005 :) I guess they're still using the same homework questions almost 7 years later.

C#
isPow2 = x && !( (x-1) & x );

See here for an explanation:
http://bytes.com/topic/c/answers/213306-test-whether-number-power-2-a[^]
 
Share this answer
 
Comments
Philip Stuyck 7-Sep-12 6:08am    
This is better than my logarithmic solution, which I deleted since this is really better. +5
Espen Harlinn 7-Sep-12 8:31am    
5'ed!
JackDingler 7-Sep-12 13:26pm    
Clever
Chuck O'Toole 7-Sep-12 15:53pm    
Assumes "x" is an integer type, doesn't work across the board for float / double
C++
v && !(v & (v - 1));

Source: http://graphics.stanford.edu/~seander/bithacks.html[^]
 
Share this answer
 
Comments
Espen Harlinn 7-Sep-12 8:31am    
5'ed!
pasztorpisti 7-Sep-12 8:42am    
Thank you!
Chuck O'Toole 7-Sep-12 15:55pm    
Assumes "v" is an integer type, doesn't work across the board for float / double
return (v % 2 == 0 ? true : false);
 
Share this answer
 
Comments
Chuck O'Toole 7-Sep-12 15:54pm    
Nope, that's a test for even / odd, multiple of 2 not power of 2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900