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

16 views (last 30 days)

Show older comments

##### 3 Comments

KALYAN ACHARJYA
on 6 Sep 2018

Edited: KALYAN ACHARJYA
on 6 Sep 2018

@Mohsin Check my answer, as per your requirement? If any modification required, let me know.

### Accepted Answer

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

##### 3 Comments

ANz Eisenheim
on 18 Nov 2020

John D'Errico
on 18 Nov 2020

@ANz Eisenheim - please don't revive dead questions with a new question. If you have a new question, then ask it separately.

Regardless, what is the problem? Generate random bits as a vector. rand can do it. randi can do it. As long as the sequence is of a length that is a multiple of 4, you are done. So WTP?

### More Answers (1)

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

##### 3 Comments

KALYAN ACHARJYA
on 6 Sep 2018

Edited: KALYAN ACHARJYA
on 6 Sep 2018

@Mohsin I have edited the answer, can you verify it?

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!