Updated with newer answer and better test
Let\'s say I have the number 382 which is 101111110.
How could I randomly turn a bit which is not 0 to
You can turn on any bit by OR'ing it with 1 and turn it off by AND'ing with the bitwise complement.
Here's an example that selects a random 1-bit and turns it off.
var rand = new Random();
int myValue = 0x017E; // 101111110b
// identify which indexes are one-bits (if any, thanks Doc)
if( myValue > 0 )
{
var oneBitsIndexes = Enumerable.Range( 0, 31 )
.Where(i => ((myValue >> i) & 0x1) !=0).ToList();
// pick a random index and update the source value bit there from 1 to 0
myValue &= ~(1 << oneBitsIndexes[rand.Next(oneBitsIndexes.Count)]);
}
// otherwise, there are no bits to turn off...