On 31/08/12 23:54, Lazar wrote:
Can someone please explain to me in what way the following function
checks if a number is a power of two? Basically, the second line of
code is what I can't really grasp:
def is_power2(num):
return num != 0 and ((num & (num - 1)) == 0)
In binary any po
Visar and Bob,
Thank you for your detailed explanations, I appreciate your help.
Kind regards,
Lazar
___
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
On 8/31/2012 6:54 PM, Lazar wrote:
Hello,
I'm fairly new to Python and still learning.
Can someone please explain to me in what way the following function
checks if a number is a power of two? Basically, the second line of
code is what I can't really grasp:
def is_power2(num):
return n
http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
You have many useful bit hacks here.
Visar Zejnullahu
On Sat, Sep 1, 2012 at 1:17 AM, Visar Zejnullahu wrote:
> 2^n in binary is 10...0 (with n 0s), and 2^n - 1 is 11...1 (with n 1s). So
> if you do bitwise and (&) to 2^n
2^n in binary is 10...0 (with n 0s), and 2^n - 1 is 11...1 (with n 1s). So
if you do bitwise and (&) to 2^n and 2^n-1 you get all 0s. That's why you
check if (num & (num - 1)) == 0.
Visar Zejnullahu
On Sat, Sep 1, 2012 at 12:54 AM, Lazar wrote:
> Hello,
>
> I'm fairly new to Python and still l
Hello,
I'm fairly new to Python and still learning.
Can someone please explain to me in what way the following function
checks if a number is a power of two? Basically, the second line of
code is what I can't really grasp:
def is_power2(num):
return num != 0 and ((num & (num - 1)) == 0)