File: bit_syntax.html

package info (click to toggle)
erlang-doc-html 1%3A11.b.2-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 23,284 kB
  • ctags: 10,724
  • sloc: erlang: 505; ansic: 323; makefile: 62; perl: 61; sh: 45
file content (385 lines) | stat: -rw-r--r-- 13,260 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.3 -->
<HTML>
<HEAD>
  <TITLE>Bit Syntax</TITLE>
  <SCRIPT type="text/javascript" src="../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
      ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="4"><!-- Empty --></A>
<H2>4 Bit Syntax</H2>
<A NAME="4.1"><!-- Empty --></A>
<H3>4.1 Introduction</H3>

<P>In Erlang a Bin is used for constructing binaries and matching
binary patterns. A Bin is written with the following syntax:
<PRE>
      &#60;&#60;E1, E2, ... En&#62;&#62;
    
</PRE>

<P>A Bin is a low-level sequence of bytes. The purpose of a Bin is
to be able to, from a high level, construct a binary,
<PRE>
Bin = &#60;&#60;E1, E2, ... En&#62;&#62;
    
</PRE>

<P>in which case all elements must be bound, or to match a binary,

<PRE>
&#60;&#60;E1, E2, ... En&#62;&#62; = Bin 
    
</PRE>

<P>where <CODE>Bin</CODE> is bound, and where the elements are bound or
unbound, as in any match.
<P>Each element specifies a certain <STRONG>segment</STRONG> of the binary.
A segment is a set of contiguous bits of the binary (not
necessarily on a byte boundary). The first element specifies
the initial segment, the second element specifies the following
segment etc.
<P>The following examples illustrate how binaries are constructed
or matched, and how elements and tails are specified.<A NAME="4.1.1"><!-- Empty --></A>
<H4>4.1.1 Examples</H4>

<P><STRONG>Example 1: </STRONG>A binary can be constructed from a set of
        constants or a string literal:
<PRE>
Bin11 = &#60;&#60;1, 17, 42&#62;&#62;,
Bin12 = &#60;&#60;&#34;abc&#34;&#62;&#62;
      
</PRE>

<P>yields binaries of size 3; <CODE>binary_to_list(Bin11)</CODE>
        evaluates to <CODE>[1, 17, 42]</CODE>, and
        <CODE>binary_to_list(Bin12)</CODE> evaluates to <CODE>[97, 98, 99]</CODE>.

<P><STRONG>Example 2: </STRONG>Similarly, a binary can be constructed
        from a set of bound variables:
<PRE>
A = 1, B = 17, C = 42,
Bin2 = &#60;&#60;A, B, C:16&#62;&#62;
      
</PRE>

<P>yields a binary of size 4, and <CODE>binary_to_list(Bin2)</CODE>
        evaluates to <CODE>[1, 17, 00, 42]</CODE> too. Here we used a
        <STRONG>size expression</STRONG> for the variable <CODE>C</CODE> in order to
        specify a 16-bits segment of <CODE>Bin2</CODE>.
<P><STRONG>Example 3: </STRONG>A Bin can also be used for matching: if
        <CODE>D</CODE>, <CODE>E</CODE>, and <CODE>F</CODE> are unbound variables, and
        <CODE>Bin2</CODE> is bound as in the former example,
<PRE>
&#60;&#60;D:16, E, F/binary&#62;&#62; = Bin2
      
</PRE>

<P>yields <CODE>D = 273</CODE>, <CODE>E = 00</CODE>, and F binds to a binary
        of size 1: <CODE>binary_to_list(F) = [42]</CODE>.
<P><STRONG>Example 4: </STRONG>The following is a more elaborate example
        of matching, where <CODE>Dgram</CODE> is bound to the consecutive
        bytes of an IP datagram of IP protocol version 4, and where we
        want to extract the header and the data of the datagram:
<PRE>
-define(IP_VERSION, 4).
-define(IP_MIN_HDR_LEN, 5).

DgramSize = size(Dgram),
case Dgram of 
    &#60;&#60;?IP_VERSION:4, HLen:4, SrvcType:8, TotLen:16, 
      ID:16, Flgs:3, FragOff:13,
      TTL:8, Proto:8, HdrChkSum:16,
      SrcIP:32,
      DestIP:32, RestDgram/binary&#62;&#62; when HLen&#62;=5, 4*HLen=&#60;DgramSize -&#62;
        OptsLen = 4*(HLen - ?IP_MIN_HDR_LEN),
        &#60;&#60;Opts:OptsLen/binary,Data/binary&#62;&#62; = RestDgram,
    ...
end.
      
</PRE>

<P>Here the segment corresponding to the <CODE>Opts</CODE> variable
        has a <STRONG>type modifier</STRONG> specifying that <CODE>Opts</CODE> should
        bind to a binary. All other variables have the default type
        equal to unsigned integer.
<P>An IP datagram header is of variable length, and its length -
        measured in the number of 32-bit words - is given in
        the segment corresponding to <CODE>HLen</CODE>, the minimum value of
        which is 5. It is the segment corresponding to <CODE>Opts</CODE>
        that is variable: if <CODE>HLen</CODE> is equal to 5, <CODE>Opts</CODE>
        will be an empty binary.
<P>The tail variables <CODE>RestDgram</CODE> and <CODE>Data</CODE> bind to
        binaries, as all tail variables do. Both may bind to empty
        binaries.
<P>If the first 4-bits segment of <CODE>Dgram</CODE> is not equal to
        4, or if <CODE>HLen</CODE> is less than 5, or if the size of
        <CODE>Dgram</CODE> is less than <CODE>4*HLen</CODE>, the match of
        <CODE>Dgram</CODE> fails.<A NAME="4.2"><!-- Empty --></A>
<H3>4.2 A Lexical Note</H3>

<P>Note that &#34;<CODE>B=&#60;&#60;1&#62;&#62;</CODE>&#34; will be interpreted as
&#34;<CODE>B =&#60; &#60;1&#62;&#62;</CODE>&#34;, which is a syntax error.
The correct way to write the expression is
&#34;<CODE>B = &#60;&#60;1&#62;&#62;</CODE>&#34;.<A NAME="4.3"><!-- Empty --></A>
<H3>4.3 Segments</H3>

<P>Each segment has the following general syntax:
<P><CODE>Value:Size/TypeSpecifierList</CODE>
<P>Both the <CODE>Size</CODE> and the <CODE>TypeSpecifier</CODE> or both may be
omitted; thus the following variations are allowed:
<P><CODE>Value</CODE>
<P><CODE>Value:Size</CODE>
<P><CODE>Value/TypeSpecifierList</CODE>
<P>Default values will be used for missing specifications.
The default values are described in the section &#34;Defaults&#34; below.

<P>Used in binary construction, the <CODE>Value</CODE> part is any
expression. Used in binary matching, the <CODE>Value</CODE> part must
be a literal or variable. You can read more about
the <CODE>Value</CODE> part in the sections about constructing
binaries and matching binaries.
<P>The <CODE>Size</CODE> part of the segment multiplied by the unit in
the <CODE>TypeSpecifierList</CODE> (described below) gives the number
of bits for the segment. In construction, <CODE>Size</CODE> is any
expression that evaluates to an integer. In matching,
<CODE>Size</CODE> must be a constant expression or a variable.
<P>The <CODE>TypeSpecifierList</CODE> is a list of type specifiers
separated by hyphens.
<P>
<DL>

<DT>
Type
</DT>

<DD>
The type can be <CODE>integer</CODE>, <CODE>float</CODE>, or
        <CODE>binary</CODE>.
</DD>

<DT>
Signedness
</DT>

<DD>
The signedness specification can be either <CODE>signed</CODE>
        or <CODE>unsigned</CODE>. Note that signedness only matters for
        matching.
</DD>

<DT>
Endianness
</DT>

<DD>
The endianness specification can be either <CODE>big</CODE>,
<CODE>little</CODE>, or <CODE>native</CODE>. Native-endian means that
        the endian will be resolved at load time to be either
big-endian or little-endian, depending on what is &#34;native&#34;
        for the CPU that the Erlang machine is run on.
</DD>

<DT>
Unit
</DT>

<DD>
The unit size is given as <CODE>unit:IntegerLiteral</CODE>.
        The allowed range is 1-256. It will be multiplied by
        the <CODE>Size</CODE> specifier to give the effective size of
        the segment.
</DD>

</DL>

<P>Example:
<PRE>
X:4/little-signed-integer-unit:8
    
</PRE>

<P>This element has a total size of 4*8 = 32 bits, and it contains
a signed integer in little-endian order.<A NAME="4.4"><!-- Empty --></A>
<H3>4.4 Defaults</H3>

<P>The default type for a segment is integer. The default
type does not depend on the value, even if the value is a
literal. For instance, the default type in '<CODE>&#60;&#60;3.14&#62;&#62;</CODE>' is
integer, not float.
<P>The default <CODE>Size</CODE> depends on the type. For integer it is
8. For float it is 64. For binary it is all of the binary. In
matching, this default value is only valid for the very last
element. All other binary elements in matching must have a size
specification.
<P>The default unit depends on the the type. For integer and
float it is 1. For binary it is 8.
<P>The default signedness is <CODE>unsigned</CODE>.
<P>The default endianness is <CODE>big</CODE>.<A NAME="4.5"><!-- Empty --></A>
<H3>4.5 Constructing Binaries</H3>

<P>This section describes the rules for constructing binaries using
the bit syntax. Unlike when constructing lists or tuples,
the construction of a binary can fail with a <CODE>badarg</CODE>
exception.
<P>There can be zero or more segments in a binary to be
constructed. The expression '<CODE>&#60;&#60;&#62;&#62;</CODE>' constructs a zero
length binary.
<P>Each segment in a binary can consist of zero or more bits.
There are no alignment rules for individual segments, but
the total number of bits in all segments must be evenly
divisible by 8, or in other words, the resulting binary must
consist of a whole number of bytes. An <CODE>badarg</CODE> exception
will be thrown if the resulting binary is not byte-aligned.
Example:
<PRE>
&#60;&#60;X:1,Y:6&#62;&#62;
    
</PRE>

<P>The total number of bits is 7, which is not evenly divisible by
8; thus, there will be <CODE>badarg</CODE> exception (and a compiler
warning as well). The following example
<PRE>
&#60;&#60;X:1,Y:6,Z:1&#62;&#62;
    
</PRE>

<P>will successfully construct a binary of 8 bits, or one byte.
(Provided that all of X, Y and Z are integers.)
<P>As noted earlier, segments have the following general syntax:

<P><CODE>Value:Size/TypeSpecifierList</CODE>
<P>When constructing binaries, <CODE>Value</CODE> and <CODE>Size</CODE> can be
any Erlang expression. However, for syntactical reasons, both
<CODE>Value</CODE> and <CODE>Size</CODE> must be enclosed in parenthesis if
the expression consists of anything more than a single literal
or variable. The following gives a compiler syntax error:
<PRE>
&#60;&#60;X+1:8&#62;&#62;
    
</PRE>

<P>This expression must be rewritten to
<PRE>
&#60;&#60;(X+1):8&#62;&#62;
    
</PRE>

<P>in order to be accepted by the compiler.<A NAME="4.5.1"><!-- Empty --></A>
<H4>4.5.1 Including Literal Strings</H4>

<P>As syntactic sugar, an literal string may be written instead
        of a element.
<PRE>
&#60;&#60;&#34;hello&#34;&#62;&#62;
      
</PRE>

<P>which is syntactic sugar for
<PRE>
&#60;&#60;$h,$e,$l,$l,$o&#62;&#62;
      
</PRE>
<A NAME="4.6"><!-- Empty --></A>
<H3>4.6 Matching Binaries</H3>

<P>This section describes the rules for matching binaries using
the bit syntax.
<P>There can be zero or more segments in a binary pattern.
A binary pattern can occur in every place patterns are allowed,
also inside other patterns. Binary patterns cannot be nested.

<P>The pattern '<CODE>&#60;&#60;&#62;&#62;</CODE>' matches a zero length binary.
<P>Each segment in a binary can consist of zero or more bits.
<P>A segment of type <CODE>binary</CODE> must have a size evenly
divisible by 8.
<P>This means that the following head will never match:
<PRE>
foo(&#60;&#60;X:7/binary-unit:1,Y:1/binary-unit:1&#62;&#62;) -&#62;
    
</PRE>

<P>As noted earlier, segments have the following general syntax:

<P><CODE>Value:Size/TypeSpecifierList</CODE>
<P>When matching <CODE>Value</CODE> value must be either a variable or
an integer or floating point literal. Expressions are not
allowed.
<P><CODE>Size</CODE> must be an integer literal, or a previously bound
variable. Note that the following is not allowed:
<PRE>
foo(N, &#60;&#60;X:N,T/binary&#62;&#62;) -&#62;
   {X,T}.
    
</PRE>

<P>The two occurrences of <CODE>N</CODE> are not related. The compiler
will complain that the <CODE>N</CODE> in the size field is unbound.
<P>The correct way to write this example is like this:
<PRE>
foo(N, Bin) -&#62;
   &#60;&#60;X:N,T/binary&#62;&#62; = Bin,
   {X,T}.
    
</PRE>
<A NAME="4.6.1"><!-- Empty --></A>
<H4>4.6.1 Getting the Rest of the Binary</H4>

<P>To match out the rest of binary, specify a binary field
        without size:
<PRE>
foo(&#60;&#60;A:8,Rest/binary&#62;&#62;) -&#62;
      
</PRE>

<P>As always, the size of the tail must be evenly divisible by 8.
<A NAME="4.7"><!-- Empty --></A>
<H3>4.7 Traps and Pitfalls</H3>

<P>Assume that we need a function that creates a binary out of a
list of triples of integers. A first (inefficient) version of
such a function could look like this:
<PRE>
triples_to_bin(T) -&#62;
    triples_to_bin(T, &#60;&#60;&#62;&#62;).

triples_to_bin([{X,Y,Z} | T], Acc) -&#62;
    triples_to_bin(T, &#60;&#60;Acc/binary, X:32, Y:32, Z:32&#62;&#62;);   % inefficient
triples_to_bin([], Acc) -&#62; 
    Acc.
    
</PRE>

<P>The reason for the inefficiency of this function is that for
each triple, the binary constructed so far (<CODE>Acc</CODE>) is
copied. (Note: The original bit syntax prototype avoided
the copy operation by using segmented binaries, which are not
implemented in R7.)
<P>The efficient way to write this function in R7 is:
<PRE>
triples_to_bin(T) -&#62;
    triples_to_bin(T, []).

triples_to_bin([{X,Y,Z} | T], Acc) -&#62;
    triples_to_bin(T, [&#60;&#60;X:32, Y:32, Z:32&#62;&#62; | Acc]);
triples_to_bin([], Acc) -&#62; 
    list_to_binary(lists:reverse(Acc)).
    
</PRE>

<P>Note that <CODE>list_to_binary/1</CODE> handles deep lists of binaries
and small integers. (This fact was previously undocumented.)<CENTER>
<HR>
<SMALL>
Copyright &copy; 1991-2006
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>