Here's my code:
is this true? I tried it and it doesn't work as it's supposed to be. So is there another easier way?Code:((num & (num - 1)) == 0)
This is a discussion on checking if a number if a power of 2 within the C Programming forums, part of the General Programming Boards category; Here's my code: Code: ((num & (num - 1)) == 0) is this true? I tried it and it doesn't ...
Here's my code:
is this true? I tried it and it doesn't work as it's supposed to be. So is there another easier way?Code:((num & (num - 1)) == 0)
Check if the square root is a whole number.
Originally Posted by phantomotap
It should work. What numbers are you using?
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
I am trying to use 3
oh nvm.. I found my self a stupid little mistake![]()
Power of two means two raised to a power, not a number raised to the second power. It's 2^x not x^2.
edit: The reason that first equation works is that any power of a number will be 1000 in that number system. 10, 100, 1000 are all powers of ten in the base-ten system. In base-two, they are all powers of two. Subtract one, and there will be a one in place of all the zeroes. 100 - 1 = 011. 100 & 011 = 0.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"