I'm trying to write a simple virtual machine that is based off a randomly generated instruction set. What would be the best way, in C, of generating a random bitmask that would contain N bits set (not the same as generating a random integer, since that is not guaranteed to have N bits set in it). I need this to work for both 16 and 32 bit integers.
Edit: It has to have exactly N bits set. Exactly. Not more. And not less. Exactly N bits set. It doesn't have to be super secure, and it doesn't have to get it's entropy from cosmic noise. It just has to be pseudorandom.
This is what I'm actually trying to achieve:
uint32_t rand_bits_32(size_t reqBits)
{
/* blah */
}
uint16_t rand_bits_16(size_t reqBits)
{
/* blah */
}
extern char *int2bin(uint32_t n, char *buf);
uint16_t gen_mask_16_excl_32(uint32_t* exclude, size_t exclude_count, size_t bits_required)
{
uint32_t ret = 0;
while (1) {
bool has = false;
ret = (uint32_t)rand_bits_16(bits_required);
for (size_t i = 0; i < exclude_count; i++) {
if (ret & (uint32_t)exclude[i]) {
has = true;
break;
}
}
if (!has) {
break;
}
has = false;
}
return ret;
}
uint32_t gen_mask_32(uint32_t* exclude, size_t exclude_count, size_t bits_required)
{
uint32_t ret = 0;
while (1) {
bool has = false;
ret = rand_bits_32(bits_required);
for (int i = 0; i < exclude_count; i++) {
if (ret & (uint32_t)exclude[i]) {
has = true;
break;
}
}
if (!has)
break;
has = false;
}
return ret;
}
I generate random bits and then bruteforce AND
them against an existing bitmask until none of the bits match, so I can generate bitmasks with N numbers of bits and that have none of the bits that are common with the other bitmasks. And yes, this code is horrible and breaks on x86_64.