Reputation: 369
i have hexdecimal data i have to convert into 64 Signed Decimal data ..so i thought have follwoing step like this. 1.hexadecimal to binary, instead of writing my own code conversion i m using code given in this link http://necrobious.blogspot.com/2008/03/binary-to-hex-string-back-to-binary-in.html
bin_to_hexstr(Bin) ->
lists:flatten([io_lib:format("~2.16.0B", [X]) ||
X <- binary_to_list(Bin)]).
hexstr_to_bin(S) ->
hexstr_to_bin(S, []).
hexstr_to_bin([], Acc) ->
list_to_binary(lists:reverse(Acc));
hexstr_to_bin([X,Y|T], Acc) ->
{ok, [V], []} = io_lib:fread("~16u", [X,Y]),
hexstr_to_bin(T, [V | Acc]).
2.binary to decimal, how to achieve this part.?
or any other way to achieve the hexdecimal -> 64 Signed Decimal data
thanx in advance
Upvotes: 6
Views: 4226
Reputation: 26121
What about this approach?
hex2int(L) ->
<< I:64/signed-integer >> = hex_to_bin(L),
I.
int2hex(I) -> [ i2h(X) || <<X:4>> <= <<I:64/signed-integer>> ].
hex_to_bin(L) -> << <<(h2i(X)):4>> || X<-L >>.
h2i(X) ->
case X band 64 of
64 -> X band 7 + 9;
_ -> X band 15
end.
i2h(X) when X > 9 -> $a + X - 10;
i2h(X) -> $0 + X.
Upvotes: 0
Reputation: 7129
To convert an integer to a hex string, just use erlang:integer_to_list(Int, 16).
To convert back, use erlang:list_to_integer(List, 16).
These functions take a radix from 2 to 36 I believe.
If you want to convert binaries to and from hex strings you can use list comprehensions to make it tidier:
bin_to_hex(Bin) -> [ hd(erlang:integer_to_list(I, 16)) || << I:4 >> <= Bin ].
hex_to_bin(Str) -> << << (erlang:list_to_integer([H], 16)):4 >> || H <- Str >>.
To convert an integer to a hex string containing a 64 bit signed integer, you can now do:
Int = 1 bsl 48, HexStr = bin_to_hex(<<Int:64/signed-integer>>),
Bin = hex_to_bin(HexStr), <<RoundTrippedInt:64/signed-integer>> = Bin,
Int =:= RoundTrippedInt.
Upvotes: 12