<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html xmlns:fn="http://www.w3.org/2005/02/xpath-functions"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../otp_doc.css" type="text/css"> <title>Erlang -- Bit Syntax</title> </head> <body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container"> <script id="js" type="text/javascript" language="JavaScript" src="../js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript"> <!-- function getWinHeight() { var myHeight = 0; if( typeof( window.innerHeight ) == 'number' ) { //Non-IE myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' myHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible myHeight = document.body.clientHeight; } return myHeight; } function setscrollpos() { var objf=document.getElementById('loadscrollpos'); document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2; } function addEvent(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, true); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } } addEvent(window, 'load', setscrollpos); //--></script><div id="leftnav"><div class="innertube"> <img alt="Erlang logo" src="../erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="../pdf/otp-system-documentation-5.9.3.1.pdf">PDF</a><br><a href="../index.html">Top</a></small><p><strong>Programming Examples</strong><br><strong>User's Guide</strong><br><small>Version 5.9.3.1</small></p> <br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p> <ul class="flipMenu" imagepath="../js/flipmenu"> <li id="no" title="Records" expanded="false">Records<ul> <li><a href="records.html"> Top of chapter </a></li> <li title="Records vs Tuples"><a href="records.html#id60765">Records vs Tuples</a></li> <li title="Defining a Record"><a href="records.html#id60728">Defining a Record</a></li> <li title="Creating a Record"><a href="records.html#id59920">Creating a Record</a></li> <li title="Accessing a Record Field"><a href="records.html#id60048">Accessing a Record Field</a></li> <li title="Updating a Record"><a href="records.html#id61983">Updating a Record</a></li> <li title="Type Testing"><a href="records.html#id60031">Type Testing</a></li> <li title="Pattern Matching"><a href="records.html#id60080">Pattern Matching</a></li> <li title="Nested Records"><a href="records.html#id61405">Nested Records</a></li> <li title="Example"><a href="records.html#id57989">Example</a></li> </ul> </li> <li id="no" title="Funs" expanded="false">Funs<ul> <li><a href="funs.html"> Top of chapter </a></li> <li title="Example 1 - map"><a href="funs.html#id64362">Example 1 - map</a></li> <li title="Example 2 - foreach"><a href="funs.html#id57513">Example 2 - foreach</a></li> <li title="The Syntax of Funs"><a href="funs.html#id61441">The Syntax of Funs</a></li> <li title="Variable Bindings Within a Fun"><a href="funs.html#id61096">Variable Bindings Within a Fun</a></li> <li title="Funs and the Module Lists"><a href="funs.html#id61883">Funs and the Module Lists</a></li> <li title="Funs Which Return Funs"><a href="funs.html#id62549">Funs Which Return Funs</a></li> </ul> </li> <li id="no" title="List Comprehensions" expanded="false">List Comprehensions<ul> <li><a href="list_comprehensions.html"> Top of chapter </a></li> <li title="Simple Examples"><a href="list_comprehensions.html#id63964">Simple Examples</a></li> <li title="Quick Sort"><a href="list_comprehensions.html#id64034">Quick Sort</a></li> <li title="Permutations"><a href="list_comprehensions.html#id64089">Permutations</a></li> <li title="Pythagorean Triplets"><a href="list_comprehensions.html#id64141">Pythagorean Triplets</a></li> <li title="Simplifications with List Comprehensions"><a href="list_comprehensions.html#id64218">Simplifications with List Comprehensions</a></li> <li title="Variable Bindings in List Comprehensions"><a href="list_comprehensions.html#id64241">Variable Bindings in List Comprehensions</a></li> </ul> </li> <li id="loadscrollpos" title="Bit Syntax" expanded="true">Bit Syntax<ul> <li><a href="bit_syntax.html"> Top of chapter </a></li> <li title="Introduction"><a href="bit_syntax.html#id64741">Introduction</a></li> <li title="A Lexical Note"><a href="bit_syntax.html#id65026">A Lexical Note</a></li> <li title="Segments"><a href="bit_syntax.html#id65049">Segments</a></li> <li title="Defaults"><a href="bit_syntax.html#id65237">Defaults</a></li> <li title="Constructing Binaries and Bitstrings"><a href="bit_syntax.html#id65297">Constructing Binaries and Bitstrings</a></li> <li title="Matching Binaries"><a href="bit_syntax.html#id65485">Matching Binaries</a></li> <li title="Appending to a Binary"><a href="bit_syntax.html#id65619">Appending to a Binary</a></li> </ul> </li> </ul> </div></div> <div id="content"> <div class="innertube"> <h1>4 Bit Syntax</h1> <h3><a name="id64741">4.1 Introduction</a></h3> <p>In Erlang a Bin is used for constructing binaries and matching binary patterns. A Bin is written with the following syntax:</p> <div class="example"><pre> <<E1, E2, ... En>></pre></div> <p>A Bin is a low-level sequence of bits or bytes. The purpose of a Bin is to be able to, from a high level, construct a binary,</p> <div class="example"><pre> Bin = <<E1, E2, ... En>></pre></div> <p>in which case all elements must be bound, or to match a binary,</p> <div class="example"><pre> <<E1, E2, ... En>> = Bin </pre></div> <p>where <span class="code">Bin</span> is bound, and where the elements are bound or unbound, as in any match.</p> <p>In R12B, a Bin need not consist of a whole number of bytes.</p> <p>A <strong>bitstring</strong> is a sequence of zero or more bits, where the number of bits doesn't need to be divisible by 8. If the number of bits is divisible by 8, the bitstring is also a binary.</p> <p>Each element specifies a certain <strong>segment</strong> of the bitstring. 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> <p>The following examples illustrate how binaries are constructed or matched, and how elements and tails are specified.</p> <h4>Examples</h4> <p><strong>Example 1: </strong>A binary can be constructed from a set of constants or a string literal:</p> <div class="example"><pre> Bin11 = <<1, 17, 42>>, Bin12 = <<"abc">></pre></div> <p>yields binaries of size 3; <span class="code">binary_to_list(Bin11)</span> evaluates to <span class="code">[1, 17, 42]</span>, and <span class="code">binary_to_list(Bin12)</span> evaluates to <span class="code">[97, 98, 99]</span>.</p> <p><strong>Example 2: </strong>Similarly, a binary can be constructed from a set of bound variables:</p> <div class="example"><pre> A = 1, B = 17, C = 42, Bin2 = <<A, B, C:16>></pre></div> <p>yields a binary of size 4, and <span class="code">binary_to_list(Bin2)</span> evaluates to <span class="code">[1, 17, 00, 42]</span> too. Here we used a <strong>size expression</strong> for the variable <span class="code">C</span> in order to specify a 16-bits segment of <span class="code">Bin2</span>.</p> <p><strong>Example 3: </strong>A Bin can also be used for matching: if <span class="code">D</span>, <span class="code">E</span>, and <span class="code">F</span> are unbound variables, and <span class="code">Bin2</span> is bound as in the former example,</p> <div class="example"><pre> <<D:16, E, F/binary>> = Bin2</pre></div> <p>yields <span class="code">D = 273</span>, <span class="code">E = 00</span>, and F binds to a binary of size 1: <span class="code">binary_to_list(F) = [42]</span>.</p> <p><strong>Example 4:</strong> The following is a more elaborate example of matching, where <span class="code">Dgram</span> 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:</p> <div class="example"><pre> -define(IP_VERSION, 4). -define(IP_MIN_HDR_LEN, 5). DgramSize = byte_size(Dgram), case Dgram of <<?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>> when HLen>=5, 4*HLen=<DgramSize -> OptsLen = 4*(HLen - ?IP_MIN_HDR_LEN), <<Opts:OptsLen/binary,Data/binary>> = RestDgram, ... end.</pre></div> <p>Here the segment corresponding to the <span class="code">Opts</span> variable has a <strong>type modifier</strong> specifying that <span class="code">Opts</span> should bind to a binary. All other variables have the default type equal to unsigned integer.</p> <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 <span class="code">HLen</span>, the minimum value of which is 5. It is the segment corresponding to <span class="code">Opts</span> that is variable: if <span class="code">HLen</span> is equal to 5, <span class="code">Opts</span> will be an empty binary.</p> <p>The tail variables <span class="code">RestDgram</span> and <span class="code">Data</span> bind to binaries, as all tail variables do. Both may bind to empty binaries.</p> <p>If the first 4-bits segment of <span class="code">Dgram</span> is not equal to 4, or if <span class="code">HLen</span> is less than 5, or if the size of <span class="code">Dgram</span> is less than <span class="code">4*HLen</span>, the match of <span class="code">Dgram</span> fails.</p> <h3><a name="id65026">4.2 A Lexical Note</a></h3> <p>Note that "<span class="code">B=<<1>></span>" will be interpreted as "<span class="code">B =< <1>></span>", which is a syntax error. The correct way to write the expression is "<span class="code">B = <<1>></span>".</p> <h3><a name="id65049">4.3 Segments</a></h3> <p>Each segment has the following general syntax:</p> <p><span class="code">Value:Size/TypeSpecifierList</span></p> <p>Both the <span class="code">Size</span> and the <span class="code">TypeSpecifier</span> or both may be omitted; thus the following variations are allowed:</p> <p><span class="code">Value</span></p> <p><span class="code">Value:Size</span></p> <p><span class="code">Value/TypeSpecifierList</span></p> <p>Default values will be used for missing specifications. The default values are described in the section <span class="bold_code"><a href="#Defaults">Defaults</a></span>.</p> <p>Used in binary construction, the <span class="code">Value</span> part is any expression. Used in binary matching, the <span class="code">Value</span> part must be a literal or variable. You can read more about the <span class="code">Value</span> part in the section about constructing binaries and matching binaries.</p> <p>The <span class="code">Size</span> part of the segment multiplied by the unit in the <span class="code">TypeSpecifierList</span> (described below) gives the number of bits for the segment. In construction, <span class="code">Size</span> is any expression that evaluates to an integer. In matching, <span class="code">Size</span> must be a constant expression or a variable.</p> <p>The <span class="code">TypeSpecifierList</span> is a list of type specifiers separated by hyphens.</p> <dl> <dt><strong>Type</strong></dt> <dd>The type can be <span class="code">integer</span>, <span class="code">float</span>, or <span class="code">binary</span>.</dd> <dt><strong>Signedness</strong></dt> <dd>The signedness specification can be either <span class="code">signed</span> or <span class="code">unsigned</span>. Note that signedness only matters for matching.</dd> <dt><strong>Endianness</strong></dt> <dd>The endianness specification can be either <span class="code">big</span>, <span class="code">little</span>, or <span class="code">native</span>. Native-endian means that the endian will be resolved at load time to be either big-endian or little-endian, depending on what is "native" for the CPU that the Erlang machine is run on.</dd> <dt><strong>Unit</strong></dt> <dd>The unit size is given as <span class="code">unit:IntegerLiteral</span>. The allowed range is 1-256. It will be multiplied by the <span class="code">Size</span> specifier to give the effective size of the segment. In R12B, the unit size specifies the alignment for binary segments without size (examples will follow).</dd> </dl> <p>Example:</p> <div class="example"><pre> X:4/little-signed-integer-unit:8</pre></div> <p>This element has a total size of 4*8 = 32 bits, and it contains a signed integer in little-endian order.</p> <h3><a name="id65237">4.4 Defaults</a></h3> <p><a name="Defaults"></a>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 '<span class="code"><<3.14>></span>' is integer, not float.</p> <p>The default <span class="code">Size</span> 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> <p>The default unit depends on the the type. For <span class="code">integer</span>, <span class="code">float</span>, and <span class="code">bitstring</span> it is 1. For binary it is 8.</p> <p>The default signedness is <span class="code">unsigned</span>.</p> <p>The default endianness is <span class="code">big</span>.</p> <h3><a name="id65297">4.5 Constructing Binaries and Bitstrings</a></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 <span class="code">badarg</span> exception.</p> <p>There can be zero or more segments in a binary to be constructed. The expression '<span class="code"><<>></span>' constructs a zero length binary.</p> <p>Each segment in a binary can consist of zero or more bits. There are no alignment rules for individual segments of type <span class="code">integer</span> and <span class="code">float</span>. For binaries and bitstrings without size, the unit specifies the alignment. Since the default alignment for the <span class="code">binary</span> type is 8, the size of a binary segment must be a multiple of 8 bits (i.e. only whole bytes). Example:</p> <div class="example"><pre> <<Bin/binary,Bitstring/bitstring>></pre></div> <p>The variable <span class="code">Bin</span> must contain a whole number of bytes, because the <span class="code">binary</span> type defaults to <span class="code">unit:8</span>. A <span class="code">badarg</span> exception will be generated if <span class="code">Bin</span> would consist of (for instance) 17 bits.</p> <p>On the other hand, the variable <span class="code">Bitstring</span> may consist of any number of bits, for instance 0, 1, 8, 11, 17, 42, and so on, because the default <span class="code">unit</span> for bitstrings is 1.</p> <div class="warning"> <div class="label">Warning</div> <div class="content"><p><p>For clarity, it is recommended not to change the unit size for binaries, but to use <span class="code">binary</span> when you need byte alignment, and <span class="code">bitstring</span> when you need bit alignment.</p></p></div> </div> <p>The following example</p> <div class="example"><pre> <<X:1,Y:6>></pre></div> <p>will successfully construct a bitstring of 7 bits. (Provided that all of X and Y are integers.)</p> <p>As noted earlier, segments have the following general syntax:</p> <p><span class="code">Value:Size/TypeSpecifierList</span></p> <p>When constructing binaries, <span class="code">Value</span> and <span class="code">Size</span> can be any Erlang expression. However, for syntactical reasons, both <span class="code">Value</span> and <span class="code">Size</span> 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:</p> <div class="example"><pre> <<X+1:8>></pre></div> <p>This expression must be rewritten to</p> <div class="example"><pre> <<(X+1):8>></pre></div> <p>in order to be accepted by the compiler.</p> <h4>Including Literal Strings</h4> <p>As syntactic sugar, an literal string may be written instead of a element.</p> <div class="example"><pre> <<"hello">></pre></div> <p>which is syntactic sugar for</p> <div class="example"><pre> <<$h,$e,$l,$l,$o>></pre></div> <h3><a name="id65485">4.6 Matching Binaries</a></h3> <p>This section describes the rules for matching binaries using the bit syntax.</p> <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> <p>The pattern '<span class="code"><<>></span>' matches a zero length binary.</p> <p>Each segment in a binary can consist of zero or more bits.</p> <p>A segment of type <span class="code">binary</span> must have a size evenly divisible by 8 (or divisible by the unit size, if the unit size has been changed).</p> <p>A segment of type <span class="code">bitstring</span> has no restrictions on the size.</p> <p>As noted earlier, segments have the following general syntax:</p> <p><span class="code">Value:Size/TypeSpecifierList</span></p> <p>When matching <span class="code">Value</span> value must be either a variable or an integer or floating point literal. Expressions are not allowed.</p> <p><span class="code">Size</span> must be an integer literal, or a previously bound variable. Note that the following is not allowed:</p> <div class="example"><pre> foo(N, <<X:N,T/binary>>) -> {X,T}.</pre></div> <p>The two occurrences of <span class="code">N</span> are not related. The compiler will complain that the <span class="code">N</span> in the size field is unbound.</p> <p>The correct way to write this example is like this:</p> <div class="example"><pre> foo(N, Bin) -> <<X:N,T/binary>> = Bin, {X,T}.</pre></div> <h4>Getting the Rest of the Binary or Bitstring</h4> <p>To match out the rest of a binary, specify a binary field without size:</p> <div class="example"><pre> foo(<<A:8,Rest/binary>>) -></pre></div> <p>The size of the tail must be evenly divisible by 8.</p> <p>To match out the rest of a bitstring, specify a field without size:</p> <div class="example"><pre> foo(<<A:8,Rest/bitstring>>) -></pre></div> <p>There is no restriction on the number of bits in the tail.</p> <h3><a name="id65619">4.7 Appending to a Binary</a></h3> <p>In R12B, the following function for creating a binary out of a list of triples of integers is now efficient:</p> <div class="example"><pre> 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.</pre></div> <p>In previous releases, this function was highly inefficient, because the binary constructed so far (<span class="code">Acc</span>) was copied in each recursion step. That is no longer the case. See the Efficiency Guide for more information.</p> </div> <div class="footer"> <hr> <p>Copyright © 2003-2012 Ericsson AB. All Rights Reserved.</p> </div> </div> </div></body> </html>