Skip to content

Instantly share code, notes, and snippets.

@sdball
Created July 19, 2016 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdball/e5f7534f40028e6026c72418a1a9e414 to your computer and use it in GitHub Desktop.
Save sdball/e5f7534f40028e6026c72418a1a9e414 to your computer and use it in GitHub Desktop.
Looking at types of Elixir byte data
is_binary <<255::size(8)>> # => true
is_bitstring <<255::size(8)>> # => true
is_binary <<255::size(4)>> # => false
is_bitstring <<255::size(4)>> # => true
# So a binary is a bitstring but a bitstring isn't necessarily a binary.
# We can see that effect in pattern matching as well:
<<255::size(4)>> # => <<15::size(4)>>
<<x>> = <<255::size(4)>> # => MatchError!
# And we can pull apart a larger byte into bits.
<<x::size(2), y::size(2)>> = <<255::size(4)>> # => <<15::size(4)>>
# This also works for utf8 bytes
<<?j>> # => "j"
<<x::size(4), y::size(4)>> = <<?j>> # => "j"
<<x,y>> # => <<6,10>> (this isn't "j" because each variable is being treated as a full byte)
<<x::size(4), y::size(4)>> # => "j" (now the bits are concatenated together into a single byte)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment