How do you randomly zero a bit in an integer?

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

    OK:

        private static Random rnd = new Random((int)DateTime.Now.Ticks);
    
        private static Int32 SetRandomTrueBitToFalse(Int32 p)
        {
            List trueBits = new List();
            for (int i = 0; i < 31; i++)
            {
                if ((p>>i&1) == 1){
                    trueBits.Add(i);
                }
            }
            if (trueBits.Count>0){
                int index = rnd.Next(0, trueBits.Count);
                return p & ~(1 << trueBits[index]);
            }
            return p;
        }
    

    But I would love to know: Why do you need/want this?

提交回复
热议问题