开发者

C#. Logical riddle with bit operations. Only one bit is set?

This should be easy for C++ people though. But I was asked how to do it in C#.开发者_高级运维 Shouldnt be much of difference.

How to find out if a long variable has only one bit set?

I cant think anything except some brutal force shifting all bits and counting whats set.


A non-negative binary integer value x is a power of 2 if (x&(x-1)) is 0 using 2's complement arithmetic.

Powers of 2 would mean a single bit is set.

http://aggregate.org/MAGIC/#Is%20Power%20of%202

EDIT:

To allow for the zero case:

bool singleBit = x>0 && (x&(x-1))==0


In C++:

unsigned long v;
bool f; // result
f = v && !(v & (v - 1));

Explanation: v & (v - 1) == 0 if only one bit is set or v == 0.


Just tried it in PHP:

$singleBit = $bits && !($bits & ($bits - 1));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜