erlang 进制转换

2041阅读 0评论2011-08-03 sunjiangang-ok
分类:Python/Ruby

    在elang中使用“#”就可以进行进制的转换,不过使用这个进行进制转换的话,只能从2~36进制之间的整数转换成10进制的数据。
    使用“#”转换的格式是:base#value。
    其中base的取值是2~36之间,value的取值是base进制下的相应数据。看一些例子吧:
  1. 60> 2#101.
  2. 5
  3. 61> 16#cafe.
  4. 51966
  5. 62> 36#fanyingfei.
  6. 1553487963263226
  7. 63> 16#fanyingfei*16#cafe.
  8. * 1: syntax error before: nyingfei
  9. 63> 36#fanyingfei*16#cafe.
  10. 80728555498936802316
  11. 64>
    使用这个我们很容易掌握的,下面我想把一个十进制的数据转换成16进制该如何做呢?
  1. %% test.erl
  2. %% Created: 2011-08-02
  3. %% Description: get Xen mac
  4. -module(test).
  5. -date("2011.08.02").

  6. %%
  7. %% Include files
  8. %%

  9. %%
  10. %% Exported Functions
  11. %%
  12. -export([list_to_hex/1]).

  13. %%
  14. %% API Functions
  15. %%
  16. list_to_hex(L) ->
    1.     lists:map(fun(X) -> int_to_hex(X) end, L).
  17. %%
  18. %% Local Functions
  19. %%
  20. int_to_hex(X) when X < 256 ->
  21.     [hex(X div 16), hex(X rem 16)].

  22. hex(N) when N < 10 ->
  23.     $0+N;
  24. hex(N) when N >= 10, N < 16 ->
  25.     $A+(N-10).
    这个程序的测试结果是这样的:
  1. 75> c(test).
  2. {ok,test}
  3. 76> test:list_to_hex([253]).
  4. ["FD"]
  5. 77> test:list_to_hex([16]).
  6. ["10"]
  7. 78> test:list_to_hex([18]).
  8. ["12"]
  9. 79>
    这样的话,我们就用erlang实现了将一个数据转换成16进制。

上一篇:Erlang App. Management with Rebar
下一篇:erlang获取一个5900——65535之间不重复的一个数据