tags:

views:

437

answers:

2

hi, 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

+2  A: 

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.
archaelus
thanx for your answer..its very good explaination of what i need..but i have one more doubt,since for this hexadecimal value 3fc2d175e1028b9a,if im writing code in php its giving 4594464874087746458 as 64 decimal value but when i m doing the same thing as you have stated hex_to_bin(Str) -> << << (erlang:list_to_integer([H], 16)):4 >> || H <- Str >>.it is giving <<63,194,209,117,225,2,139,154>>.so any explanation for this ..please tell me whats wrong on this.
Abhimanyu
<<I:64/signed>> = hex_to_bin("3fc2d175e1028b9a"), I =:= 4594464874087746458. -- You just need to convert the binary to an integer in erlang (the << numbers >> notation indicates a binary).
archaelus
A: 

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.
Hynek -Pichi- Vychodil