天天看點

erlang二進制文法點滴

Erlang/OTP 17 [erts-6.0] [source] [smp:2:2] [async-threads:10] [kernel-poll:false]

Eshell V6.0  (abort with ^G)

1> <<100,200,300,400>>.

<<100,200,44,144>>

2> <<100,200,300:16,400:16>>.

<<100,200,1,44,1,144>>

說明了一個segment預設是8位,高于8位的部分被截斷

同理

1> A = <<15768105>>.

<<")">>

2> io:format("~.16B", [15768105]).

F09A29ok

16進制29是10進制的41,由此可以看出<<15768105>>其實等于<<41>>

但是

1> <<41>> = <<15768105>>.

<<")">>

2> <<15768105>> = <<41>>.

** exception error: no match of right hand side value <<")">>

3>  <<1:1>> = <<3:1>>.

<<1:1>>

4> <<3:1>> = <<1:1>>.

** exception error: no match of right hand side value <<1:1>>

5> <<5:2>> = <<13:2>>.

** exception error: no match of right hand side value <<1:2>>

6> A = <<15768105>>.

<<")">>

7> B = <<41>>.

<<")">>

8> A = B.

<<")">>

這些該如何解釋呢?

-------------------------------------------------

& 基本形式:

Value:Size/TypeSpecifierList

TypeSpecifierList包括

Type(integer, float, binary, bitstring),

Signedness(signed, unsigned),

Endianness(big, little, native),

Unit(1-256)

e.g.

X:4/little-signed-integer-unit:8

<<X:4/big-signed-float-unit:16>> = <<100.5/float>>.

& 預設值

類型預設為integer

Size的預設項:

integer預設8位,float預設64位

binary或bitstring處于尾部時預設比對全部

Unit的預設項:

integer和float和bitstring為1, binary為8

Signedness預設為unsigned

Endianness預設為big

& 詞法注意

B=<<1>>需要寫成B = <<1>>

<<X+1:8>>需要寫成<<(X+1):8>>

比對時Value和Size必須是常量或已綁定的變量

下面的形式會報N is unbound錯,

foo(N, <<X:N,T/binary>>) ->

   {X,T}.

正确的寫法:

foo(N, Bin) ->

   <<X:N,T/binary>> = Bin,

   {X,T}.

& Unit

最好不要改binary和bitstring的Unit

& 文法糖

<<"hello">>是<<$h,$e,$l,$l,$o>>的文法糖

& 常用寫法

取尾部的寫法:

foo(<<A:8,Rest/binary>>) ->

foo(<<A:8,Rest/bitstring>>) ->

高效拼binary的寫法:

triples_to_bin(T) ->

    triples_to_bin(T, <<>>).

triples_to_bin([{X,Y,Z} | T], Acc) ->

    triples_to_bin(T, <<Acc/binary,X:32,Y:32,Z:32>>);   % inefficient before R12B

triples_to_bin([], Acc) ->

    Acc.

參照:http://www.erlang.org/doc/programming_examples/bit_syntax.html

轉載于:https://www.cnblogs.com/suex/p/3699181.html