'How can I get random numbers between 1-7 in kernel using get_random_bytes()?

int random_ticket;
get_random_bytes(&random_ticket, sizeof(random_ticket));

I tried to do it like this but I think this method gives random numbers between 0 and infinity. I am not so sure about how to get random numbers between 1 and 7.

Can you please explain how can I do it?



Solution 1:[1]

Use unsigned math to reduce the range to [1...7]

%, the remainder operator is like a mod operator when used in unsigned math. Useful to reduce the range to 7 different values. A slight bias is introduced though as the typical 232 number of different values of an unsigned is not a multiple of 7.

unsigned random_ticket;

// () not needed with sizeof object
get_random_bytes(&random_ticket, sizeof random_ticket); 

// Best to use unsigned constants with unsigned objects.
random_ticket = 1u + (random_ticket % 7u); 

Do not use a signed int and random_ticket = 1 + (random_ticket % 7); as random_ticket % 7 returns values in the [-6 ... 6] range.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1