Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why if (n & -n) == n then n is a power of 2?

Line 294 of java.util.Random source says

if ((n & -n) == n) // i.e., n is a power of 2     // rest of the code 

Why is this?

like image 951
David Weng Avatar asked Sep 13 '11 16:09

David Weng


People also ask

What is the meaning of if n?

(archaic) Contraction of if and when.

How do you prove that N is even?

In addition, we have some variations of these basic styles of proofs. Definition: An integer n is called even if and only if there exists an integer k such that n=2k. An integer n is called odd if and only if there exists an integer k such that n=2k+1. Theorem: If n is an odd integer, then n2 is an odd integer.


1 Answers

Because in 2's complement, -n is ~n+1.

If n is a power of 2, then it only has one bit set. So ~n has all the bits set except that one. Add 1, and you set the special bit again, ensuring that n & (that thing) is equal to n.

The converse is also true because 0 and negative numbers were ruled out by the previous line in that Java source. If n has more than one bit set, then one of those is the highest such bit. This bit will not be set by the +1 because there's a lower clear bit to "absorb" it:

 n: 00001001000 ~n: 11110110111 -n: 11110111000  // the first 0 bit "absorbed" the +1         ^         |         (n & -n) fails to equal n at this bit. 
like image 186
Steve Jessop Avatar answered Oct 01 '22 02:10

Steve Jessop