有什么方法可以做到以下几点?二进制 - >列表 - >二进制似乎没必要.
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)]).
Run Code Online (Sandbox Code Playgroud)
如果不关心性能,你的代码绝对没问题。否则你可以做一些不同的事情。
例如 Erlang 支持任意大小的整数:
binary_and(A, B) ->
Size = bit_size(A),
<<X:Size>> = A,
<<Y:Size>> = B,
<<(X band Y):Size>>.
Run Code Online (Sandbox Code Playgroud)
或者您可以手工制作自己的二进制 zip 例程:
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.
Run Code Online (Sandbox Code Playgroud)
或者优化版本:
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.
Run Code Online (Sandbox Code Playgroud)
或更复杂的
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.
Run Code Online (Sandbox Code Playgroud)
无论如何,你必须衡量一下你是否真的对性能感兴趣。对于您的目的来说,第一个可能是最快的。
| 归档时间: |
|
| 查看次数: |
2765 次 |
| 最近记录: |