Efficient way of generating a random number of N (less than 64) bits with exactly M bits equal to one Would there be an efficient way to implement a function with the following signature: 

unsigned long long int random_word(size_t n, size_t m)


that would generate a random machine word (64 bits here) such that exactly m bits over the n least significant ones at set to 1. For example: random_word(10, 3) would generate a 64-bit random number such that 3 bits over the 10 LSBs are set to 1. For a given n and m every possible output should have equal probability (uniform distribution of possible permutations).

If assembly bit twiddling hacks to do that are known, great, if not, I am looking for references and research directions.
I'd guess that you can simply split this into two problems:


create 64 - n random bits, call this R
shuffle n bits where m bits (at any location) are set to 1, call this P


Finally you can simply perform R | P (presuming big endian notation).

Shuffling lists of elements is an operation present in almost any language. If there is any inefficiency it would be in the shuffling algorithm (although Fisher-Yates is optimal, so you'd expect some form of that algorithm, possibly the inefficiency is getting values in a range...).