[erlang-questions] bit syntax

Dmitry Klionsky <>
Fri Nov 30 09:26:25 CET 2012


Hi!

All below comes from 
http://www.erlang.org/doc/programming_examples/bit_syntax.html

...
Value:Size
...
The Size part of the segment multiplied by the unit in the 
TypeSpecifierList (described below) gives the number of bits for the 
segment. In construction, Size is any
expression that evaluates to an integer. In matching, Size must be a 
constant expression or a variable.
...


And (2*8) is a legal Size:

7> <<Length, Value:(2*8)>> = X.
<<2,1,0>>

This works because (2*8) really evaluates at compile time and it equals to

<<Length, Value:16>> = X.



12> <<Length, Value:(Length*8)>> = X.
* 1: illegal bit size

The expression (Length*8) is supported when constructing a binary. This 
is definitely a pattern matching, so as stated above: the Size must be a 
constant expression or a variable. Not an expression to be evaluated at 
runtime.

As a workaround you can do this

 > <<Length, Rest/binary>> = X.
 > ValueLen = Length*8.
 > <<Value:ValueLen>> = Rest.



76> << [49, 50, 51, 52] >>.
** exception error: bad argument

77> X = "1234".
"1234"

78> <<X>>.
** exception error: bad argument

The only way you can do this is

list_to_binary([49, 50, 51, 52]).
and
list_to_binary("1234").



BR,
Dmitry


On 11/30/2012 09:20 AM, 7stud wrote:
> Hi,
>
> I have a couple of questions about the bit syntax.
>
> 1) I can read the first byte of a binary to get the length of the next value:
>
> 1> X = <<16, 256:16>>.
> <<16,1,0>>
>
> 2> <<Length, Value:Length>> = X.
> <<16,1,0>>
>
> 3> Length.
> 16
>
> 4> Value.
> 256
>
>
>
> And (2*8) is a legal Size:
>
> 5> f().
> ok
>
> 6> X = <<2, 256:16>>.
> <<2,1,0>>
>
> 7> <<Length, Value:(2*8)>> = X.
> <<2,1,0>>
>
> 8> Length.
> 2
>
> 9> Value.
> 256
>
>
> So why does Size = Length*8 fail when Length=2?
>
> 10> f(Length).
> ok
>
> 11> f(Value).
> ok
>
> 12> <<Length, Value:(Length*8)>> = X.
> * 1: illegal bit size
>
>
>
>
> 2)  What is going on here:
>
>
> 73> f().
> ok
>
> 74> <<"1234">>.
> <<"1234">>
>
> 75> "1234" == [49, 50, 51, 52].
> true
>
> 76> << [49, 50, 51, 52] >>.
> ** exception error: bad argument
>
> 77> X = "1234".
> "1234"
>
> 78> <<X>>.
> ** exception error: bad argument
>
> In line 74, I can use a string while constructing a binary, but in 76 I can't use the equivalent list.  And in line 77, when I bind the string to a variable, I can't use the variable to construct a binary.
>
> Thanks.
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions


-- 
Best regards,
Dmitry Klionsky




More information about the erlang-questions mailing list