How to generate a random number of n bits length?

22 次查看(过去 30 天)
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?
  3 个评论
Mohsin Shah
Mohsin Shah 2018-9-6
For n = 3 then the output range is [0-7] which includes the range [0-3] which is for n = 2
KALYAN ACHARJYA
KALYAN ACHARJYA 2018-9-6
编辑:KALYAN ACHARJYA 2018-9-6
@Mohsin Check my answer, as per your requirement? If any modification required, let me know.

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2018-9-6
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 个评论
ANz Eisenheim
ANz Eisenheim 2020-11-18
I want generate a random large sequence of bits and block the sequence. each block of data consisting of 4 bits. Can Anyone help?
John D'Errico
John D'Errico 2020-11-18
@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?

请先登录,再进行评论。

更多回答(1 个)

KALYAN ACHARJYA
KALYAN ACHARJYA 2018-9-6
编辑:KALYAN ACHARJYA 2018-9-6
function bit_result=rand_bits(n)
result=randi([2^(n-1), 2^n]);
bit_result=de2bi(result,n)
end
  3 个评论
KALYAN ACHARJYA
KALYAN ACHARJYA 2018-9-6
编辑:KALYAN ACHARJYA 2018-9-6
@Mohsin I have edited the answer, can you verify it?
Mohsin Shah
Mohsin Shah 2018-9-6
I appreciate your efforts but the edited function still doesn't work. Check the answer of Guillaume which worked for me.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Sources 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by