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.
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.
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?
1> binary_to_list(<<255,0,0,0,0,1>>).
[255,0,0,0,0,1]
For example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With