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

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -