[erlang-questions] bit syntax

7stud 7stud@REDACTED
Fri Nov 30 07:20:47 CET 2012


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.



More information about the erlang-questions mailing list