2009-12-17 12 views
5

Qual è il modo migliore per fare quanto segue? Binary -> list -> binary sembra non necessario.Operazioni binarie sui binari di Erlang?

binary_and(A, B) -> 
    A2 = binary_to_list(A), 
    B2 = binary_to_list(B), 
    list_to_binary([U band V || {U, V} <- lists:zip(A2, B2)]). 
+2

usare l'opzione 'bin_opt_info' durante la compilazione di ottenere alcuni suggerimenti di ottimizzazione utilizzo binario. Vedere il manuale di compilazione per i dettagli. – Zed

risposta

3

Se non si cura delle prestazioni, il codice è assolutamente OK. Altrimenti puoi fare qualcosa di diverso.

Per esempio Erlang supporta interi di dimensione arbitraria:

binary_and(A, B) -> 
    Size = bit_size(A), 
    <<X:Size>> = A, 
    <<Y:Size>> = B, 
    <<(X band Y):Size>>. 

Oppure si può artigianato propria routine zip binario:

binary_and(A,B) -> binary_and(A, B, <<>>). 

binary_and(<<A:8, RestA/bytes>>, <<B:8, RestB/bytes>>, Acc) -> 
    binary_add(RestA, RestB, <<Acc/bytes, (A band B):8>>); 
binary_and(<<>>, <<>>, Result) -> Result. 

o ottimizzate versione:

binary_and(A,B) -> binary_and(A, B, <<>>). 

binary_and(<<A:64, RestA/bytes>>, <<B:64, RestB/bytes>>, Acc) -> 
    binary_add(RestA, RestB, <<Acc/bytes, (A band B):64>>); 
binary_and(<<A:8, RestA/bytes>>, <<B:8, RestB/bytes>>, Acc) -> 
    binary_add(RestA, RestB, <<Acc/bytes, (A band B):8>>); 
binary_and(<<>>, <<>>, Result) -> Result. 

o più sofisticato

binary_and(A,B) -> binary_and({A, B}, 0, <<>>). 

binary_and(Bins, Index, Acc) -> 
    case Bins of 
    {<<_:Index/bytes, A:64, _/bytes>>, <<_:Index/bytes, B:64, _/bytes>>} -> 
     binary_add(Bins, Index+8, <<Acc/bytes, (A band B):64>>); 
    {<<_:Index/bytes, A:8, _/bytes>>, <<_:Index/bytes, B:8, _/bytes>>} -> 
     binary_add(Bins, Index+1, <<Acc/bytes, (A band B):8>>); 
    {<<_:Index/bytes>>, <<_:Index/bytes>>} -> Acc 
    end. 

In ogni caso è necessario misurare se si è veramente interessati alle prestazioni. Potrebbe essere il primo è il più veloce per i tuoi scopi.

3

Se volete vedere il potere del lato oscuro ...

binary_and(A, B) -> 
    Size = erlang:byte_size(A), 
    Size = erlang:byte_size(B), 
    Res = hipe_bifs:bytearray(Size, 0), 
    binary_and(Res, A, B, 0, Size). 

binary_and(Res, _A, _B, Size, Size) -> 
    Res. 

binary_and(Res, A, B, N, Size) -> 
    Bin = hipe_bifs:bytearray_sub(A, N) band hipe_bifs:bytearray_sub(B,N), 
    hipe_bifs:bytearray_update(Res, N, Bin), 
    binary_and(Res, A, B, N+1, Size). 
Problemi correlati