Integer to Binary Erlang

被刻印的时光 ゝ 提交于 2019-12-05 12:45:46

问题


I am trying to make an integer into a binary:

543 = <<"543">>

How can I do this without

integer_to_list(list_to_binary(K)).

回答1:


If you want to convert 543 to <<"543">> I don't think you can find something faster than:

1> list_to_binary(integer_to_list(543)).
<<"543">>

Because in this case both functions implemented in C.

If you want to convert integer to the smallest possible binary representation you can use binary:encode_unsigned function from the new binary module like this:

1> binary:encode_unsigned(543).
<<2,31>>
2> binary:encode_unsigned(543, little).
<<31,2>>



回答2:


For current readers, this is now implemented in R16, see http://erlang.org/doc/man/erlang.html#integer_to_binary-1




回答3:


You can try something like

6> A = 12345.                       
12345
7> B = <<A:32>>.
<<0,0,48,57>>

But this requires you to know the maximum number of bits in advance.



来源:https://stackoverflow.com/questions/4010713/integer-to-binary-erlang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!