How do you randomly zero a bit in an integer?

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

    Count all the 1's in your integer. Choose a random number using your favorite random number generator between 1 and the first count. Create a mask for Random-th 1 in your integer. OR your integer with the mask.

提交回复
热议问题