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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The description is not entirely accurate because
(0 & -0) == 0but 0 is not a power of two. A better way to say it is((n & -n) == n)when n is a power of two, or the negative of a power of two, or zero.If n is a power of two, then n in binary is a single 1 followed by zeros.
-n in two’s complement is the inverse + 1 so the bits lines up thus
To see why this work, consider two’s complement as inverse + 1,
-n == ~n + 1since you carry the one all the way through when adding one to get the two’s complement.
If n were anything other than a power of two† then the result would be missing a bit because the two’s complement would not have the highest bit set due to that carry.
† – or zero or a negative of a power of two … as explained at the top.