How do you randomly zero a bit in an integer?

后端 未结 13 1918
無奈伤痛
無奈伤痛 2021-02-05 10:11

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

13条回答
  •  名媛妹妹
    2021-02-05 10:47

    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...
    

提交回复
热议问题