2009-06-08 96 views
5

我有十六進制數據我必須轉換爲64有符號的十進制數據..所以我認爲有這樣的follwoing步驟。 1.hexadecimal二進制, 而不是寫我自己的代碼轉換I M使用在這個環節http://necrobious.blogspot.com/2008/03/binary-to-hex-string-back-to-binary-in.html十六進制到64有符號十進制

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爲十進制定的代碼, 如何實現這一目標的一部分。?

或任何其他方式來實現hexdecimal - > 64個符號十進制數據

thanx提前

回答

11

要的整數轉換爲十六進制字符串,只需使用erlang:integer_to_list(Int, 16).要轉換回來,使用erlang:list_to_integer(List, 16).這些函數我相信從2到36的基數。

如果你想二進制轉換,並從十六進制的字符串,您可以使用列表內涵,使之更爲簡潔:

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 >>. 

要將整數轉換爲包含64位有符號整數十六進制字符串,您現在可以做:

Int = 1 bsl 48, HexStr = bin_to_hex(<<Int:64/signed-integer>>), 
Bin = hex_to_bin(HexStr), <<RoundTrippedInt:64/signed-integer>> = Bin, 
Int =:= RoundTrippedInt. 
+0

thanx您answer..its什麼,我need..but我還有一個疑問,很好的交代,因爲這個十六進制值3fc2d175e1028b9a,如果在PHP我寫的代碼它給4594464874087746458 64十進制值,但當你做同樣的事情時,你已經說過hex_to_bin(Str) - ><< <<(erlang:list_to_integer([H],16)):4 >> || H <- Str >>。 它給出了<< 63,194,209,117,225,2,139,154 >>,所以對此的任何解釋都請告訴我這是什麼錯誤。 – Abhimanyu 2009-06-09 04:14:38

0

這種方法呢?

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. 
相關問題