Erlang bit string and binary data

Source: Internet
Author: User

http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=25876834&id=3300393

Because in my work, the server Erlang and the client flash communication is to send binary data (protocol) to communicate, Erlang processing binary data is really convenient, in the free time to view and translate Erlang binary related to some of the documentation, There are, of course, places where you can understand your own experience and knowledge.

in the binary parsing section, there are a number of good examples. Also is Erlang's binary actual application example, next time will share, translation is not in place, also please correct, the original addressHttp://www.erlang.org/doc/programming_examples/bit_syntax.html#id64786,http://www.erlang.org/doc/reference_ manual/expressions.html#id79300

Click (here) to collapse or open

  1. Erlang bit string and binary data
  2. Bit strings (bitstring) are made up of bits, which are understood to be ' bits ', and do not require the number of bits to be divisible by 8, and if exactly divisible by 8, then the bit string is a binary.
  3. Each digit in a bit string is in a defined segment, a segment consists of a contiguous number of bits (no bounds between segments), such as the first segment, followed by the second segment.
  4. The following example illustrates the construction of binary data, matching, and how to obtain and use elements from binary data.
  5. 1. A few simple examples
  6. Example One :
  7. A binary data consisting of a set of constants or simple strings
  8. Bin11 = <<1, n, 42>>
  9. Bin12 = << "abc" >>
  10. The resulting binary data size of 3,binary_to_list (BIN11) is calculated as [1, +,], and the Binary_to_list (BIN22) calculation results are [97, 98, 99].
  11. Example Two :
  12. Similarly, a binary data can also consist of a set of bound variables
  13. A = 1, B = +, C = 42,
  14. Bin2 = <<a, B, c:16>>
  15. The resulting binary data size of 4,binary_to_list (BIN2) evaluates to [1, 17, 0, 42]. Here C uses the dimension expression, which specifies that the segment C occupies 16 bits in the binary data, that is, two units of length.
  16. example Three :
  17. Binary data is also available for matching operations. Assuming that d,e,f is a free variable, Bin2 is a variable in the example two:
  18. <<d:16, E, f/binary>> = Bin2
  19. Result d = 273, (because D contains a, b two segments, the binary is converted to 10 after the result of the binary), E = 0,f = 42 (here on my machine is <<*>> my Erlang version is newer than the version on the document)
  20. 2. Note
  21. The syntax should be noted that the "b=<<1>>" notation is understood by the Erlang compiler as "B =< <1>>", which produces a syntax error. The correct wording should be "B = <<1>>".
  22. 3. Introduction to the various parts of the binary data
  23. Bit string, each segment follows a common syntax format, as follows:
  24. Value:size/typespecifierlist Value: Size/Type
  25. Because size and typespeciferlist do not have to be specified, they can be omitted at the time of writing, and the following format is correct:
  26. Value
  27. Value:size
  28. Value/typespecifierlist
  29. When no specification is specified, the default value (the default specification, which can also be understood as the default syntax convention) is used. The default value is explained below
  30. When constructing a binary data structure, value can be any expression, and in binary matching operations, value must be a normal word (literal) or variable.
  31. Size indicates how many bits the segment is, and if typespecifierlist (type) is indicated, the number of unit lengths represented by size, size must be an integer.
  32. Typespecifierlist consists of a set of attributes separated by '-', which can be composed of four parts:
  33. Type, can be Integer, Float, Binary
  34. Signedness the rules are unsigned or signed
  35. Endianness Specify byte storage sequence
  36. Unit length, must be divisible by size
  37. Such as:
  38. X:4/little-signed-integer-unit:8
  39. The total size of X is 4 * 8 =
  40. 4. Default (Convention)
  41. The data type of each segment in the binary is integer by default, and the default type does not depend on the value, even if the value is a word.
  42. Similarly, the type of "<<3.14>>" is also an integer, not a floating-point type.
  43. The default size (size) is determined by the type, the integer is 8, the float is 64, and if the binary type is the entire length of the binary. In a match operation, only the last piece of data is valid using the default size, and the data segments in other locations must specify the size.
  44. The default unit length, integer and floating-point are 1,binary 8.
  45. Default is unsigned
  46. The default byte sequence is the big head arrangement
  47. 5. Construct a binary and bit string (bitstring)
  48. Constructing the binary syntax is not the same as creating lists and tuples, and if the arguments are wrong, they will burst "badarg" errors.
  49. A binary can consist of one or more segments, and 0 segments "<<>>" represent binary data of zero size (in many cases, we will send an empty binary as a signal to trigger no event).
  50. <<Bin/binary,Bitstring/bitstring>>
  51. Such a data, the size of the bin must be 8-bit integer multiples, and the size of the bitstring must be 1 integer times.
  52. The following data:
  53. <<x:1, y:6>>
  54. It is possible to construct a bit string with a size of 7bit, and make a special point:
  55. <<X+1:8>> is wrong and should be written:
  56. << (x+1):8>>
  57. << "Hello" >> equivalent to << $h, $e, $l, $l, $o >>, the former is syntactically more convenient than the latter (syntax sugar)
  58. 6. Binary Data matching operations
  59. When matching operations, remember that size must be an integer or a bound variable (the value is an integer), as
  60. Foo (N, <<X:N,T/binary>>)
  61. {x,t}.
  62. This is wrong because, at compile time, n is not bound as size.
  63. The right approach:
  64. Foo (N, Bin)
  65. <<X:N,T/binary>> = Bin,
  66. {x,t}.
  67. 7. Get the remainder of a binary and bit string
  68. Foo (<<A:8,Rest/binary>>)
  69. The size of rest must be divisible by 8.
  70. Foo (<<A:8,Rest/bitstring>>)
  71. The size of rest is not strictly limited.
  72. 8. Bit string parsing (bit string comprehensions)
  73. Bit string parsing, like List parsing, is a very efficient way to generate new bit strings, the general syntax is as follows:
  74. << bitstring | | Qualifier1,..., Qualifiern >>
  75. Bitstring a valid bit string expression, qualifier is a bit string generator or filter
  76. Generic generators (such as list parsing inside), usually writing:
  77. Pattern <-listexpr.
  78. and the bit string generator writes:
  79. Bitstringpattern <= bitstringexpr.
  80. Of course, here bitstringexpr must be a legitimate bit string expression.
  81. A filter is an expression that returns TRUE or False
  82. Specific examples are:
  83. << << (x*2) >> | | <<X>> <= << >> >>;.
  84. <<2,4,6>>
  85. 1.BIF:
  86. BIF: (built-in function) built-in functions are part of the Erlang language. is the basic operation in an Erlang virtual machine.
  87. TUPLE_TO_LIST/1 converts a tuple to a list, time/0 returns the current time, minutes, seconds.
    1> tuple_to_list ({12,cat, "ddd"}).
    [12,cat, "ddd"]
    3> time ().
    {12,35,57}

    2. Binary data:
    A data type used to achieve high-speed storage of raw data. Save memory and input and output more efficiently. When writing a print, the binary data appears as an integer or sequence of characters, surrounded by angle brackets, respectively. One of the integers, each one to be between 0-255, if the binary data is a printable string, the shell will display a string, otherwise a string of integers will be displayed.

    @spec describes the parameters and return types of the function. Type callouts, rather than Erlang code, are part of the comment document and cannot be used in the shell. Module declarations in Erlang are also part of the annotations.

    Erlang constructs binary data or extracts data from it through BIF, or through bit syntax to complete the process.
    @spec list_tbo_inary (iolist), binary ()
    @spec split_binary (Bin,pos), {bin1,bin2}
    @spec term_to_ Binary (term), bin
    @spec binary_to_term (bin), term
    List_tbo_inary converts everything in iolist to a binary data. Split_binary splits binary data into two parts at the POS location. The following two are reciprocal.

    4> Bin1 = <<1,2,3>>.
    <<1,2,3>>
    5> Bin2 = <<4,5>>.
    <<4,5>>
    6> Bin3 = <<6>>.
    <<6>>
    7> list_to_binary ([bin1,1,[2,3,bin2],4| Bin3]).
    <<1,2,3,1,2,3,4,5,4,6>>
    12> split_binary (<<1,2,3,1,2,3,4,5,4,6>>,4).
    {<<1,2,3,1>>,<<2,3,4,5,4,6>>
    14> term_to_binary ({One, ' 333a ', use}).
    <<131,104,3,97,11,100,0,4,51,51,51,97,100,0,3,117,115,101>>
    15> binary_to_term (<< 131,104,3,97,11,100,0,4,51,51,51,97,100,0,3,117,115,101>>).
    {One, ' 333a ', use}
    returns the binary data byte length
    16> size (<<1,2,3,4>>).
    4
    3. Bit syntax
    bit syntax: A pattern-matching syntax for bits in binary data for packet-and-packet work. The
    bit syntax is an extension of pattern matching. When writing the underlying code, it is often necessary to packet-unpack the bit-level binary data, which will reflect the convenience of bit syntax and the bit syntax designed for protocol programming (Erlang's housekeeping skills-wow plug).
    Packet unpacking of 16bit colors

    19> Red = 2.
    2
    20> Green = 54.
    54
    21> Blue = 20.
    20
    22> men = <<red:5,green:6,blue:5>>.
    <<22,212>>
    23> Mem = <<red:5,green:5,blue:5>>.
    <<21,84:7>>
    24> <<R1:5,G1:6,B1:5>> = men.
    <<22,212>>
    25> R1.
    2
    27> G1.
    54
    28> B1.
    20

    You can see that you are using: To make a match, before the colon is the data, and then the number of bits that are occupied.

    Bit-Syntax expressions

    Well, here's the bit syntax format:

    The form of bit syntax:<<>> or <<e1,e2,e3,e4,..., en>>. There are four types of EI:

    Ei = Value | Value:size | Value/typespecifierlist | Value:size/typespecifierlist

    The total number of bits in the binary data is exactly divisible by 8 (each byte in binary data is 8bit). Value must be a bound variable, a text string, or an integer that returns a value. Expressions for floating-point and binary data. Size must be an integer or integer bound variable, not a free variable. The integer default size is 8, the float type is 64, and the binary is its own length. Specifierlist determines the byte order, and the value is:

    @type End = big| Little |native

    The book gives an example of how these three sorts and the default sort, different machines may be different.

    37> {<<16#12345678:32/big>>,<<16#12345678:32/little>>,<<16#12345678:32/native >>,<<16#12345678:32>>}.
    {<<18,52,86,120>>,
    <<120,86,52,18>>,
    <<120,86,52,18>>,
    <<18,52,86,120>>}

    4. Summary of Use

    Block expression:

    Begin
    EXPR1,
    ....
    Exprn
    End

    The chunk value is the value of the last expression in the fast, used when a single expression is allowed somewhere in the code and you want to use a string of expressions.

    Comments:

    Only line Comment%, no block comment.

    List operator ++--: infix operator for adding and removing lists.

    Comparison expressions:

    The size comparison order is defined for all types:

    Number<atom<reference<fun<port<pid<tuple<list<binary

    Role: You can sort the list that stores any type and write efficient data access code based on the order of comparison.

    Outside the =:=,=/=, the others follow the following rules:

    If a comparison parameter is an integer, another floating-point number, the integer needs to be converted to a floating-point number before comparison.

    If the two comparison parameters are integers or floating-point numbers, direct comparison ...

    = = Applies only to the comparison of floating-point numbers and integers. It's best to use =:=.

    Underline variable:

    If a variable is used only once in a sentence, the compiler warns. But the underscore starts, and the compiler does not produce a warning message.

    Name the variable that is not ready for use, increasing readability. Easy to Debug.

Erlang bit string and binary data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.