elixir

How do you get the length of a binary in Elixir?


How to you get the length of a binary in bytes? It's not a string. I don't want the number of characters. I just want to know how many bytes long it is.


Solution

  • You could leverage byte_size for that purpose as documented here

    Returns the number of bytes needed to contain bitstring.

    That is, if the number of bits in bitstring is not divisible by 8, the resulting number of bytes will be rounded up (by excess). This operation happens in constant time.

    Allowed in guard tests. Inlined by the compiler.

    Examples

    iex> byte_size(<<433::16, 3::3>>) 3

    iex> byte_size(<<1, 2, 3>>)