Skip to content

Instantly share code, notes, and snippets.

@zhongwencool
Created January 7, 2016 11:24
Show Gist options
  • Save zhongwencool/659442f5e51a22c97ae1 to your computer and use it in GitHub Desktop.
Save zhongwencool/659442f5e51a22c97ae1 to your computer and use it in GitHub Desktop.
%%%-------------------------------------------------------------------
%%% @author zhongwencool@gmail.com
%%% @copyright (C) 2016, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 06. 一月 2016 18:30
%%%-------------------------------------------------------------------
-module(hex).
%% API
-compile(export_all).
-define(RUN_TIMES, 100000).
hexstr_to_bin(S) ->
hexstr_to_bin(S, []).
hexstr_to_bin([], Acc) ->
list_to_binary(lists:reverse(Acc));
hexstr_to_bin([$ |T], Acc) ->
hexstr_to_bin(T, Acc);
hexstr_to_bin([X, Y|T], Acc) ->
{ok, [V], []} = io_lib:fread("~16u", [X, Y]),
hexstr_to_bin(T, [V | Acc]).
hexbin_to_bin(S) ->
hexbin_to_bin(S, <<>>).
hexbin_to_bin(<<>>, Acc) -> Acc;
hexbin_to_bin(<<$ , Rest/binary>>, Acc) -> hexbin_to_bin(Rest, Acc);
hexbin_to_bin(<<X, Y, Rest/binary>>, Acc) ->
{ok, [V], []} = io_lib:fread("~16u", [X, Y]),
hexbin_to_bin(Rest, <<Acc/binary, V>>).
test() ->
Bin = <<"349906e74209e823228f0025ae99f0d9d2c406a523d6415d1087ae313c3d7539">>,
Str = "349906e74209e823228f0025ae99f0d9d2c406a523d6415d1087ae313c3d7539",
io:format("~p~n", [hexbin_to_bin(Bin) == hexstr_to_bin(Str)]),
{TimeBin,_} = timer:tc(fun() -> hexstr_to_bin_test(?RUN_TIMES) end),
{TimeStr,_} = timer:tc(fun() -> hexbin_to_bin_test(?RUN_TIMES) end),
io:format("BinTime:~p StrTime:~p Diff:~p~n",[TimeBin, TimeStr, TimeBin- TimeStr]).
hexstr_to_bin_test(0) -> ok;
hexstr_to_bin_test(N) ->
hexstr_to_bin("349906e74209e823228f0025ae99f0d9d2c406a523d6415d1087ae313c3d7539"),
hexstr_to_bin_test(N-1).
hexbin_to_bin_test(0) -> ok;
hexbin_to_bin_test(N) ->
hexbin_to_bin(<<"349906e74209e823228f0025ae99f0d9d2c406a523d6415d1087ae313c3d7539">>),
hexbin_to_bin_test(N-1).
@zhongwencool
Copy link
Author

(zhongwencool@zhongwen)1> hex:test().
true
BinTime:1927792 StrTime:2175268 Diff:-247476
ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment