Decode a trail of <<Header, Length, Payload, ......, Header, Length, Payload,.......>> from Binary Input

Papa Tana papa.tana101@REDACTED
Wed Jul 15 00:28:06 CEST 2020


Hi,

You are right, I was doing it twice.
I removed and it works!

Anyway, possible values of Header ranges from 0x01 to 0x98, so if I
have to check these values 1 by 1, I will die.....

Your first suggestion is suitable for my use case, no need to check, I
can get the values in Result directly:

Data =
	<<
		1, 3:8, "a", "a", "a",
		2, 4:16, "a", "a", "a", "a",
		3, 6:24, "a", "a", "a", "a", "a", "a",
		4, 2:32, "a", "a"
	>>,

decode(Data).

decode(<<Header:8, X/binary>>) ->
    L = Header*8,
    <<Length:L/integer, Payload:Length/binary, Rest/binary>> = X,
    [{Header, Length, Payload} | pdecode(Rest)];
pdecode(<<>>) ->
    [].

Thanks EveryBody,
Really kind of you, it saved me from 1000+ lines of code...

Best Regards,

2020-07-15 0:59 UTC+03:00, Jesper Louis Andersen
<jesper.louis.andersen@REDACTED>:
> On Tue, Jul 14, 2020 at 11:44 PM Papa Tana <papa.tana101@REDACTED> wrote:
>
>>                                         << _:8, Length1:8, Rest1/binary
>> >>
>> = Data,
>>                                         NumberOfOctets1 = Length1*8,
>>
>>                                         << _:8, _:8,
>> Content1:NumberOfOctets1, Rest11/binary>> = Rest1,
>>                                         {ok,
>> <<Header:8,Length1:8,Content1:NumberOfOctets1>>, Rest11};
>>
>
> There are two problems here you are running into:
>
> First, you split Data into a header, a length and the rest. But then you
> split Rest1 again, skipping the header and length. So you are skipping
> twice over the header and the length. You need to remove `_:8, _:8` because
> you already stripped that off when you hand in Rest1.
>
> The other problem is that when you write `Content1:NumberOfOctets1` Erlang
> defaults that to an integer, but you probably want a binary (and they
> default to a multiple of 8 octet size, so you could write
> `Content1:Length1/binary`.
>


More information about the erlang-questions mailing list