# How to generate a random number of n bits length?

46 views (last 30 days)
Mohsin Shah on 6 Sep 2018
Commented: Mohsin Shah on 6 Sep 2018
Let's say a function takes input n as the bit length and outputs a random number. For example, for n = 4, the output range is [0 - 15] which also includes the range for n = 3 i.e. [0 - 7]. The function should generate the number in the range [8 - 15] and not in the range [0 - 15]. How to do this and how to generalize it for any n?

KALYAN ACHARJYA on 6 Sep 2018
The function should generate the number in the range [8 - 15] and not in the range [0 - 15]. How to do this and how to generalize it for any n?
Can you clarify this statement? if n=3 then ??
What I am getting you want three-bit representation(when n=3) in the range [8 - 15]??
Mohsin Shah on 6 Sep 2018
For n = 3 then the output range is [0-7] which includes the range [0-3] which is for n = 2
KALYAN ACHARJYA on 6 Sep 2018
@Mohsin Check my answer, as per your requirement? If any modification required, let me know.

Guillaume on 6 Sep 2018
For n = 4 it should generate a number in the range [8-15]
If I understand correctly, you want a 4 bit random number with the MSB always set to 1. That sounds like a strange requirement, probably not thought properly, but this is simply equivalent to generating a 3 bit random number and tacking 1 as the MSB. The generic version of that (generating a n-1 bit number + MSB of 1) is:
n = 4
number = randi([1, 2^(n-1)]) + 2^(n-1) - 1

#### 1 Comment

Mohsin Shah on 6 Sep 2018
It worked for me. Thank you.

KALYAN ACHARJYA on 6 Sep 2018
Edited: KALYAN ACHARJYA on 6 Sep 2018
function bit_result=rand_bits(n)
result=randi([2^(n-1), 2^n]);
bit_result=de2bi(result,n)
end