erlang - checksum
Godd Morning,
I am trying to perform a check sum on the following function
Data = [<<"9">>,"81",
<<1>>,
<<"52=">>,
[[50,48,49,48,49,48,50,54,45,49,53,":",52,53,":",52,52]],
<<1>>,
<<1>>,
[<<"9">>,<<"0">>,<<1>>],
[<<"5">>,<<"4">>,<<1>>]]
Using:
checksum(Data) -> checksum(Data, 0).
checksum([H | T], Acc) ->
if
is_binary(H) ->
I = binary_to_list(H);
true ->
I = H
end,
checksum(T, I + Acc);
checksum([], Acc) -> Acc.
It basically needs to break the Data down into discrete numbers
ideally it would look like [56,45,34,111,233,...]
and then add them all together.
Th开发者_运维百科e compiler gives me errors no matter what I try. I had it solved before it was very simple, but now one change up the food chain affected this.
Please help, and best wishes!
Try the following code:
checksum(Data) -> checksum(iolist_to_binary(Data), 0).
checksum(<<I, T/binary>>, Acc) -> checksum(T, I + Acc);
checksum(<<>>, Acc) -> Acc.
If you need to compute standard CRC like CRC32 or Adler-32 you can use erlang:crc32 and erlang:adler32 BIFs like this:
1> Data = [<<"9">>,"81",
1> <<1>>,
1> <<"52=">>,
1> [[50,48,49,48,49,48,50,54,45,49,53,":",52,53,":",52,52]],
1> <<1>>,
1> <<1>>,
1> [<<"9">>,<<"0">>,<<1>>],
1> [<<"5">>,<<"4">>,<<1>>]]
1> .
[<<"9">>,"81",
<<1>>,
<<"52=">>,
[[50,48,49,48,49,48,50,54,45,49,53,":",52,53,":",52,52]],
<<1>>,
<<1>>,
[<<"9">>,<<"0">>,<<1>>],
[<<"5">>,<<"4">>,<<1>>]]
2> erlang:adler32(Data).
1636173186
3> erlang:crc32(Data).
3649492735
It's also worth to consider erlang:phash2 BIF:
4> erlang:phash2(Data).
38926910
5> erlang:phash2(Data, 65536).
64062
if
is_binary(H) ->
I = binary_to_list(H);
true ->
I = H
Here you're setting I
to H
which might be a list or binary_to_llist(H)
, which is definitely a list.
checksum(T, I + Acc);
You're adding I
and Acc
, but I
might be a list. You can't add a list to a number.
You should set I to be the checksum of H
if H
is a list or the checksum of binary_to_list(H)
if H
is a binary.
checksum([A|B]) -> checksum(A) + checksum(B);
checksum([]) -> 0;
checksum(<<A, B/binary>>) -> A + checksum(B);
checksum(<<>>) -> 0;
checksum(A) -> A.
精彩评论