How do you randomly zero a bit in an integer?

后端 未结 13 1898
無奈伤痛
無奈伤痛 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:36

    Try the following code

    public static int ChangeOneBit(int data)
    {
        if (data == 0)
        {
            return data;
        }
    
        var random = new Random();
        int bit = 0;
        do
        {
            var shift = random.Next(31);
            bit = data >> shift;
            bit = bit & 0x00000001;
        } while (bit == 0);
        var ret = data & (~(1 << bit));
        return ret;
    }
    

提交回复
热议问题