Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir binary pattern matching of Integer or Convert Integer to binary

I just started learning today Elixir and stuck in pattern matching of Integer.

I know well how to match binary, but I can't find how to match Integer i.e. extract high byte from a simple Integer. I must either convert an Integer to binary or write a function which takes a high byte from Integer, but found nothing close in the library.

<<y1::size(8), y2::size(8),  y3::size(8), y4::size(8) >> = t

where t is Integer as you may guess gives

** (MatchError) no match of right hand side value: 3232235521
like image 503
Dmitry Dyachkov Avatar asked Mar 28 '17 14:03

Dmitry Dyachkov


Video Answer


1 Answers

You can convert an integer to binary using <<x::32>> (which is short for <<x::size(32)>>). This will convert using the Big Endian byte order. For Little Endian, you need to add -little, like <<x::little-32>>. You can then extract using the pattern you already mentioned (again I shortened it to remove size() as 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 you already have an integer, you can also extract these bytes using Bitwise operators, but 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
like image 99
Dogbert Avatar answered Dec 09 '22 20:12

Dogbert