anonymous
anonymous

Reputation: 57

Extract the first N elements of a binary in Erlang

Can someone please tell me how to get the first 4 characters in the following binary list in Erlang:

<<245,185,198,200,52,227,138,93,250>>

Upvotes: 0

Views: 1057

Answers (3)

Odobenus Rosmarus
Odobenus Rosmarus

Reputation: 5998

1> M = <<245,185,198,200,52,227,138,93,250>>.
<<245,185,198,200,52,227,138,93,250>>
2> <<A,B,C,D, _/binary>> = M.
<<245,185,198,200,52,227,138,93,250>>
3> A.
245
4> B.
185
5> C.
198
6> D.
200
7> 

Upvotes: 0

Eugen Dubrovin
Eugen Dubrovin

Reputation: 906

there is two ways:

1)

split binary to list -

[245,185,198,200,52,227,138,93,250] = binary_to_list(<<245,185,198,200,52,227,138,93,250>>).
{"õ¹ÆÈ",[52,227,138,93,250]} = lists:split(4, [245,185,198,200,52,227,138,93,250]).

2)

or get the direct binary part

<<"õ¹ÆÈ">> = binary:part(<<245,185,198,200,52,227,138,93,250>>, 0, 4).

3)

if you need exact 4 numbers - you may use this function

[A, B, C, D | _Tail] = binary_to_list(<<245,185,198,200,52,227,138,93,250>>).

2> A.
245
3> B.
185
4> C.
198
5> D

Upvotes: 0

dbc
dbc

Reputation: 61

Use Bit Syntax:

<< R:4/binary,_/binary >> = <<245,185,198,200,52,227,138,93,250>>.

Upvotes: 6

Related Questions