[erlang-questions] bit operations/matching

Kostis Sagonas kostis@REDACTED
Thu May 8 20:19:39 CEST 2008


Pieter Erlang wrote:
> Hi,
> 
> Can someone explain why line 2 fails (and line 3 not)?
> (also reproducible in other ways)
> 
> 
> Erlang (BEAM) emulator version 5.6.2 [async-threads:0]
> 
> Eshell V5.6.2 (abort with ^G)
> 1> B = <<0:1000>>.
> <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
> 0,...>>
> 2> <<_:80,Val:2,_/binary>> = B.
> ** exception error: no match of right hand side value
> <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
> 0,...>>

Till a point, Erlang supported only binaries == sequences of bytes.
Till then, the type qualifier that was to be used for matching against a 
  sequence of bytes was "binary".

Starting with R12, this type qualifier has been properly renamed "bytes" 
(but "binary" has been maintained for backwards compatibility reasons) 
so that programmers like Pieter Erlang are less likely to be confused by 
matching failures:

-------------------------------------------------------------------------
Eshell V5.6.3  (abort with ^G)
1> B = <<0:1000>>.
<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
   0,...>>
2> <<_:80,Val:2,_/binary>> = B.
** exception error: no match of right hand side value 
<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                                                         0,...>>
3> <<_:80,Val:2,_/bytes>> = B.
** exception error: no match of right hand side value 
<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                                                         0,...>>
-------------------------------------------------------------------------

I would strongly recommend that programs using "binary" get changed to 
"bytes".

If one really wants bit level pattern matching, the qualifier "bits" has 
been added for that purpose:

-------------------------------------------------------------------------
4> <<_:80,Val:2,_/bits>> = B.
<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
   0,...>>
5> <<_:13,Val:69,_/bits>> = B.
<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
   0,...>>
-------------------------------------------------------------------------


Kostis



More information about the erlang-questions mailing list