Parsing null terminated strings in a binary.
Raimo Niskanen
raimo@REDACTED
Thu Jan 13 14:34:25 CET 2005
You are missing nothing. The code just evolved in my head to
what it became - some cruft was left. This might be even clearer
(untested):
z_split(B, N) when is_binary(B), is_integer(N) ->
case B of
<<B1:N/binary,0,B2/binary>> ->
{B1,B2};
_ when size(B) > N
z_split(B, N+1);
_ ->
B
end.
mats.cronqvist@REDACTED (Mats Cronqvist) writes:
> i don't get the last two matches. i'd think this would work;
>
> z_split(B, N) ->
> case B of
> <<B1:N/binary,0,B2/binary>> -> {B1, B2};
> <<_:N/binary>> -> B;
> _ -> z_split(B, N+1)
> end.
>
> what am i missing?
>
> mats
>
> Raimo Niskanen wrote:
> > ... and this actually compiles and works:
> > [code]
> > z_split(B, N) ->
> > case B of
> > <<B1:N/binary,0,B2/binary>> ->
> > {B1,B2};
> > <<_:N/binary>>=B ->
> > B;
> > <<_:N/binary,_/binary>>=B ->
> > z_split(B, N+1)
> > end.
> > [/code]
> > Eshell V5.4.3 (abort with ^G)
> > 1> t:z_split(<<61,62,63,0,64,65,66>>, 0).
> > {<<61,62,63>>,
> > <<64,65,66>>}
> > 2> t:z_split(<<61,62,63,0,64>>, 0). {<<61,62,63>>,
> > <<64>>}
> > 3> t:z_split(<<61,62,63,0>>, 0). {<<61,62,63>>,
> > <<>>}
> > 4> t:z_split(<<61,62,63>>, 0). <<61,62,63>>
> > Raimo Niskanen <raimo@REDACTED> writes:
> >
> >>Parse the binary in a loop something like this (untested):
> >>
> >>z_split(<<B1:N/binary,0,B2/binary>>, N) ->
> >> {B1,B2};
> >>z_split(<<B1:N/binary>>, N) ->
> >> B1;
> >>z_split(<<_:N/binary,_/binary>>=B, N) ->
> >> z_split(B, N+1).
> >>
> >>This will not build any sub-binaries until the zero is found.
> >>
> >>
> >>
> >>cyberlync@REDACTED (Eric Merritt) writes:
> >>
> >>
> >>>Guys,
> >>>
> >>> I have a need to parse out a series of null terminated fields a
> >>>binary. The easiest way to do this is to simply traverse the binary
> >>>using bit syntax until a null byte occurs. However, I believe this
> >>>would be less then efficient as a new binary would be created for
> > each
> >
> >>>byte matched. Aside from created a C port to actually do the parsing
> >>>do any of you have any ideas on how to do this efficiently?
> >>>
> >>>Thanks,
> >>>Eric
> >>> --
> >>>I'm a programmer, I don't have to spell correctly; I just have to
> >>>spell consistently
> >>
> >> --
> >>
> >>/ Raimo Niskanen, Erlang/OTP, Ericsson AB
> >
--
/ Raimo Niskanen, Erlang/OTP, Ericsson AB
More information about the erlang-questions
mailing list