[erlang-questions] bit syntax: what does "<<1234>> =" match?
Robert Virding
robert.virding@REDACTED
Sat Feb 26 20:28:57 CET 2011
----- "Loïc Hoguin" <essen@REDACTED> wrote:
> On 02/26/2011 06:04 PM, Anthony Ramine wrote:
>> Le 26 févr. 2011 à 17:37, Anton Lebedevich a écrit :
>>
>> As I said, the thing on the left is a pattern, so I think it actually compiles to
>> "a binary which the only byte's value is 1234", which obviously won't ever match
>> anything.
>>
>> That could be the intended behaviour as much as it could be a bug, IMHO.
>
> What about this:
>
> 9> <<1234:8>> = <<1234:8>>.
> ** exception error: no match of right hand side value <<"Ò">>
> 10> <<1234:16>> = <<1234:16>>.
The behaviour is not a bug, it is rather an effect of how the expression is evaluated. The first thing to be aware of is that expressions in the shell are not compiled but are interpreted, done in the module erl_eval. This explains any differences between compiled code and the shell.
In this case Anton is close. When tryin to match a binary the matcher first uses the bitspecs in the binary pattern to extract a value, then it tries to match it against the value given in the pattern.
In the first case it extracts the first 8 bit integer from the binary, 210, and tries to match it against 1234, which fails. In the second it extracts the first 16 bit integer, 1234, which suceeds. If the pattern had been <<12.34/float>> it would have extracted the first 64 bits as a float and tried to match it against 12.34.
One of the cool things with binaries is that there is no info in the binary saying how it was created so I can do lots of fun things when I pull it apart.
Robert
--
Robert Virding, Erlang Solutions Ltd.
More information about the erlang-questions
mailing list