1
votes

This seems like a simple question, and I might be missing something obvious, but I can't figure out how to make a function in Elixir that returns a random byte. I want something like:

def random_byte do
  <<0>>..<<255>> |> Enum.random()
end

But you can't make a range with binaries. I could just manually type out a list of all 256, but I was hoping there was a better way to do it.

1

1 Answers

5
votes

You mean a binary with one byte? You can put Enum.random(0..255) inside the <<>>:

iex(1)> <<Enum.random(0..255)>>
<<181>>
iex(2)> <<Enum.random(0..255)>>
"x"

Another way would be to use :crypto.strong_rand_bytes/1 (might be slower but this is also cryptographically secure):

iex(3)> :crypto.strong_rand_bytes(1)
<<205>>
iex(4)> :crypto.strong_rand_bytes(1)
"7"