erlang The Bit Syntax 学习

 

爷爷在书上是这样描述的

The bit syntax is an extension to pattern matching used for extracting
and packing individual bits or sequences of bits in binary data. When
you’re writing low-level code to pack and unpack binary data at a bit
level, you’ll find the bit syntax incredibly useful. The bit syntax was
developed for protocol programming (something that Erlang excels at)
and produces highly efficient code for packing and unpacking protocol
data.
Suppose we have three variables—X, Y, and Z—that we want to pack
into a 16-bit memory area in a variable M. X should take 3 bits in the
result, Y should take 7 bits, and Z should take 6. In most languages
this involves some messy low-level operations involving bit shifting and
masking. In Erlang, you just write the following:
M = <<X:3, Y:7, Z:6>>
Easy!

Eshell V5.7.4  (abort with ^G)
1> X =1.
1
2> Y=2.
2
3> Z=3.
3
4> M = <<X:2,Y:2,Z:6>>.   
<<96,3:2>>
5> <<X1:2,Y1:1,Z1:7>> = M.
<<96,3:2>>
6> Z1.
3
7> Y1.
1
8> X1.
1
9> <<X2:2,Y2:7,Z2:1>> = M.
<<96,3:2>>
10> Z2.
1
11> Y2.
65
12> X2.
1
13> 
14>  <<X3:2,Y3:2,Z3:6>> = M.
<<96,3:2>>
15> Z3.
3
16> Y3.
2
17> X3.
1


过了一把隐,Z3,Y3,X3 解析出来 的值与 Z,Y,X是一样的 其他的不对,因为“位数”变化了
继续往下看发现这么一段话
Whatever form you use, the total number of bits in the binary must be
evenly divisible by 8。
郁闷了 我的位数不是8的倍数,
4> M = <<X:2,Y:2,Z:6>>. 我这里总共是 2+2+6 =10 并不是8的倍数 
*大头(82400***) 15:35:17
01100000,11 
*大头(82400***) 15:35:49
所以有2个bit裸奔了 (可以操作裸奔的位,也就是不是8的倍数的剩下的位)
*大头(82400***) 15:36:02
3:2就是这个意思,后面的11 



Bit Syntax Expressions
Bit syntax expressions are of the following form:
<<>>
<<E1, E2, ..., En>>
Each element Ei specifies a single segment of the binary. Each element
Ei can have one of four possible forms:
Ei = Value |
Value:Size |
Value/TypeSpecifierList |
Value:Size/TypeSpecifierList
Whatever form you use, the total number of bits in the binary must be
evenly divisible by 8. (This is because binaries contain bytes that take
up 8 bits each, so there is no way of representing sequences of bits
whose length is not a multiple of 8.)


 

 

你可能感兴趣的:(erlang,UP)