Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hex to 64 Signed Decimal

Tags:

erlang

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

like image 735
Abhimanyu Avatar asked Jun 08 '09 13:06

Abhimanyu


People also ask

How do you convert signed binary to decimal?

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.

How do you convert hex to 2's complement?

To find hexadecimal 2's complement:Subtract the number from FFFFFFFF. Add 1.


1 Answers

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.
like image 74
archaelus Avatar answered Oct 10 '22 17:10

archaelus