How do you randomly zero a bit in an integer?

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

    Here's a slightly more efficient version using bit twiddling.

        public static int getBitCount(int bits)
        {
            bits = bits - ((bits >> 1) & 0x55555555);
            bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333);
            return ((bits + (bits >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
        }
    
        public static int flipRandomBit(int data)
        {
            int index = random.Next(getBitCount(data));
            int mask = data;
    
            for (int i = 0; i < index; i++)
                mask &= mask - 1;
            mask ^= mask & (mask - 1);
    
            return data ^ mask;
        }
    

提交回复
热议问题