bit manipulation - Alt answer to classic bitwise 2^n test: valid? -
Quick question: I used to test single-n for format 2 ^ n (n> = 0) Press the line expression.
See:
An associate came up with this unorthodox answer:
((n-1) xor n == 2 * n - 1 ) & Amp; Amp; (n! = 0) I used a test to test it, and it seems right. I almost tested almost n = 10000
Does anyone see any problem with this solution? I can not find this reference online.
Thank you!
- David
In fact you all input (For example, using an SMT solver) should be tested. There are 31 cases in which this formula is correct even though n does not have the power of two, in cases where the top bit is set, apart from some other bit. For example, 0xC0000000 or 0x80000001. n ^ (n - 1) A known method is "Remove the right set bit and tidy it to the right". Among the cases I have described, n * 2 - 1 is one of the same mistakes, the upper bit is moved and the smear on the right side of -1 (because bit now One is on the left side where it was to be).
Comments
Post a Comment