Search code examples
binaryerlangpattern-matchingbitstring

Erlang 0 bitstring pattern matching


How do you pattern match a bitstring that equals 0 in erlang? In other words patterns of the form:

<<0:17>>
<<0:1>>
<<0:N>>

This is for defining a function.

Thanks


Solution

  • Here is a workaround, I hope it helps:

    -module(lab).
    -compile(export_all).
    
    is_zero_bitstring(BitString) ->
        Size = erlang:bit_size(BitString),
        <<0:Size>> =:= BitString.
    

    Run it from within the Erlang shell:

    1> c(lab).
    {ok,lab}
    2> lab:is_zero_bitstring(<<0:17>>).
    true
    3> lab:is_zero_bitstring(<<0:1>>). 
    true
    4> lab:is_zero_bitstring(<<0:123456>>).  
    true
    5> lab:is_zero_bitstring(<<7>>).   
    false