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
A signed binary number is converted into a decimal using the following procedure: The significant (n - 1) position of the bits are raised to the power of two and then added to obtain the decimal result. If the most significant position is 0 then it's a positive number, otherwise the number is negative.
To find hexadecimal 2's complement:Subtract the number from FFFFFFFF. Add 1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With