Elixir binary pattern matching of Integer or Convert Integer to binary -
i started learning today elixir , stuck in pattern matching of integer.
i know how match binary, can't find how match integer i.e. extract high byte simple integer. must either convert integer binary or write function takes high byte integer, found nothing close in library.
<<y1::size(8), y2::size(8), y3::size(8), y4::size(8) >> = t
where t integer may guess gives
** (matcherror) no match of right hand side value: 3232235521
you can convert integer binary using <<x::32>>
(which short <<x::size(32)>>
). convert using big endian byte order. little endian, need add -little
, <<x::little-32>>
. can extract using pattern mentioned (again shortened remove size()
it's not required):
iex(1)> <<y1::8, y2::8, y3::8, y4::8>> = <<3232235521::32>> <<192, 168, 0, 1>> iex(2)> {y1, y2, y3, y4} {192, 168, 0, 1} iex(3)> <<y1::8, y2::8, y3::8, y4::8>> = <<3232235521::little-32>> <<1, 0, 168, 192>> iex(4)> {y1, y2, y3, y4} {1, 0, 168, 192}
since have integer, can extract these bytes using bitwise operators, it's way less readable:
iex(1)> use bitwise bitwise iex(2)> n = 3232235521 3232235521 iex(3)> n &&& 0xff 1 iex(4)> n >>> 8 &&& 0xff 0 iex(5)> n >>> 16 &&& 0xff 168 iex(6)> n >>> 24 &&& 0xff 192
Comments
Post a Comment