Nathaniel Waisbrot
Nathaniel Waisbrot

Reputation: 24473

Interpret binary value as an integer

I have a function that seems to expect an integer, but I have a binary value. Can I tell Erlang to interpret the binary as an integer?

How could I get this code to work (in the REPL)?

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

Upvotes: 1

Views: 305

Answers (2)

Ning
Ning

Reputation: 2880

Here is a shorter version:

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

Upvotes: 3

legoscia
legoscia

Reputation: 41527

You can use a bit syntax expression to extract integers from binaries:

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

Read the full description and some examples in the reference manual.

Upvotes: 5

Related Questions