Daniel Lovasko
Daniel Lovasko

Reputation: 481

Erlang generate random binary

What is the most efficient way to generate a random binary object given a number of bits? I understand that the crypto:rand_bytes function would be an option, but the bit count must not necessarily be a multiply of 8.

Upvotes: 2

Views: 1386

Answers (2)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26131

rand_bits(Bits) ->
    Bytes = (Bits + 7) div 8,
    <<Result:Bits/bits, _/bits>> = crypto:rand_bytes(Bytes),
    Result.

Upvotes: 6

A. Sarid
A. Sarid

Reputation: 3996

One way that you will be able to do it is:

<<(rand:uniform(MaxNum)):(rand:uniform(MaxBits))>>

Or same way if you wish to use the crypto module:

<<(crypto:rand_uniform(MinNum, MaxNum)):(crypto:rand_uniform(MinBits, MaxBits))>>

Upvotes: 0

Related Questions