Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 686
Boppity Bop Avatar asked Jan 07 '11 09:01

Boppity Bop


2 Answers

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
like image 179
spender Avatar answered Oct 05 '22 23:10

spender


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.

like image 21
Antti Avatar answered Oct 05 '22 23:10

Antti