Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang bitstring to integer conversion

Tags:

erlang

I have an erlang bitstring based on the network representation of a MAC address, e.g. <<255,0,0,0,0,1>>, and would like to convert it to an integer. What is the most efficient way to go about this conversion?

Thanks, Matt.

like image 251
mpm Avatar asked Feb 04 '11 14:02

mpm


3 Answers

You can choose how much data you pack/match by using the :Size and -unit:N options:

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 unpack pretty much whatever you want.

like image 71
I GIVE TERRIBLE ADVICE Avatar answered Nov 04 '22 08:11

I GIVE TERRIBLE ADVICE


Read it out:

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

Though it does not match the number you want. Perhaps due to some floating point rounding error?

like image 30
I GIVE CRAP ANSWERS Avatar answered Nov 04 '22 10:11

I GIVE CRAP ANSWERS


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

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

For example.

like image 24
benc.tamas Avatar answered Nov 04 '22 08:11

benc.tamas