将二进制值解释为整数

时间:2013-08-21 14:11:29

标签: erlang

我有一个似乎期望整数的函数,但我有一个二进制值。我可以告诉Erlang将二进制解释为整数吗?

我怎样才能使这段代码工作(在REPL中)?

Binary = <<"hello world">>.
Integer = binary_to_integer(Binary).  % fix me
Increment = Integer + 1.

2 个答案:

答案 0 :(得分:5)

您可以使用位语法表达式从二进制文件中提取整数:

2> Binary = <<"hello world">>.
<<"hello world">>
3> Bits = bit_size(Binary).
88
4> <<Integer:Bits>> = Binary.
<<"hello world">>
5> Integer.
126207244316550804821666916
6> Increment = Integer + 1.
126207244316550804821666917
7> <<Increment:Bits>>.
<<"hello worle">>

阅读the reference manual中的完整说明和一些示例。

答案 1 :(得分:3)

这是一个较短的版本:

> crypto:bytes_to_integer(<<"hello world">>).
126207244316550804821666916