[erlang-questions] Binary manipulation

Michael Santos <>
Sun Mar 13 12:09:20 CET 2011


On Fri, Mar 11, 2011 at 09:01:38AM +0000, Bob Cowdery wrote:
> Hi
> 
> I would appreciate any advice/ideas on how to efficiently handle a large
> binary.
> 
> The binary in question has a couple of protocol wrappers around it which
> are no problem as the bit syntax easily copes with that. What I'm not
> sure of is how to handle the data.
> 
> <<I:24, Q:24, M:16 ... repeated 63 times >>
> 
> What I have to do is extract I and Q which are 24 bit le values and end
> up with another binary which is:
> 
> <<I/float, Q/float ... repeated 63 times (see below) >>
> 
> Where I and Q are now floating point numbers. I will need M in the
> future, but not right now. It's a little more complicated than that
> because several of the raw data binaries will go into the processed
> binary which will be a multiple of 64 up to 1024.
> 
> I will also need to do the opposite, i.e. take the processed binary and
> transform it back to the raw data binary.

Maybe something like this would work:

% Using a list
m(Bin) ->
    m(Bin, []).
     
% Assume big endian
m(<<>>, Acc) ->
    list_to_binary(lists:reverse(Acc));
m(<<I:24/little, Q:24/little, _M:16, Rest/binary>>, Acc) ->
    m(Rest, [<<I/float, Q/float>>|Acc]).
              

% Or constructing a binary each time
m1(Bin) ->
    m1(Bin, <<>>).
                    
m1(<<>>, Acc) ->
    Acc;
m1(<<I:24/little, Q:24/little, _M:16, Rest/binary>>, Acc) ->
    m1(Rest, <<Acc/binary, I/float, Q/float>>).



More information about the erlang-questions mailing list