开发者

Erlang bitstring to integer conversion

I have an erlang bitstring based on the network representation of a MAC address, e.g. <<255,0,0,0,0,1>&开发者_开发问答gt;, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜