Erlang bitstring for integer conversion

I have an erlang bit string based on the network representation of a MAC address, for example. <<255,0,0,0,0,1>>and would like to convert it to an integer. What is the most efficient way to do this conversion?

Thanks Matt.

+5
source share
3 answers

Read:

2> <<N:48/integer>> = <<255,0,0,0,0,1>>.
<<255,0,0,0,0,1>>
3> N.
280375465082881

Although it does not match the desired number. Perhaps due to some floating point rounding error?

+13
source

You can choose how much data you are packing / matching using the options :Sizeand -unit:N:

1> <<X:6/integer-unit:8>> = <<255,0,0,0,0,1>>.
<<255,0,0,0,0,1>>
2> X.
280375465082881

Or more dynamically:

3> Bin = <<255,0,0,0,0,1>>.                 
<<255,0,0,0,0,1>>
4> Size = size(Bin). 
6
5> <<Int:(Size)/integer-unit:8>> = Bin.     
<<255,0,0,0,0,1>>
6> Int.
280375465082881

Using these variable sizes, you can unzip almost anything you want.

+14

1 > binary_to_list (< 255,0,0,0,0,1 → ).

[255,0,0,0,0,1]

.

+1