tags:

views:

81

answers:

2

Erlang doesn't let me do:

Type = bitstring. 
<<FirstPart:8/Type, Rest/bitstring>> = some_binary.

although it lets me do:

Size = 8. 
<<FirstPart:Size/bitstring, Rest/bitstring>> = some_binary.

So, in bit string expressions, while I can pass the size through a variable, It doesnt let me pass the type through a variable. Is there any solution?

A: 

I do not see anything extraordinary here that makes a conditional inconvenient for handling the different "types" of encoding.

case StringType of
  byte_len ->
    <<Len:8, String:Len/binary>> = SomeBinary,
    String;
  word_len ->
    <<Len:32, String:Len/binary>> = SomeBinary,
    String;
  etc -> ...
end
Christian
+3  A: 

You can use a case statement as a workaround:

{FirstPart, Rest} = case Type of
                        {'bitstring', Len} ->
                            <<A:Len/bitstring, B/bitstring>> = Bin,
                            {A,B};
                        'integer' ->
                            <<A/integer, B/bitstring>> = Bin,
                            {A,B};
                        ...
Zed
This works for me, and i already have done it like this. I was just wondring why they havent made it possible to use a var for the type...
Paralife
My _guess_ is that the binary expressions are compiled into something internal at compilation time.
Zed
@Zed is right, binary expressions are compiled and not having the type would make it slow.
rvirding