Most efficient method of generating a random number with a fixed number of bits set

前端 未结 6 1922
清歌不尽
清歌不尽 2020-12-16 03:44

I need to generate a random number, but it needs to be selected from the set of binary numbers with equal numbers of set bits. E.g. choose a random byte value with exactly 2

6条回答
  •  醉话见心
    2020-12-16 04:28

    Say the number of bits to set is b and the word size is w. I would create a vector v of of length w with the first b values set to 1 and the rest set to 0. Then just shuffle v.

提交回复
热议问题