[erlang-questions] using variable in bit syntax

Haobo Yu haoboy@REDACTED
Sat Jul 14 23:38:07 CEST 2007


That link is very helpful.  Thanks!

- Haobo

On Jul 14, 2007, at 12:01 AM, Gaspar Chilingarov wrote:

> Haobo Yu wrote:
>> Hi,
>> I'm rather new to erlang, so please pardon my ignorance.
>> I'm trying to parse a packet header using the bit syntax.  There  
>> is a  byte in the header that indicates the endianness of the  
>> subsequent  integers in the packet header.  For example:
>> endianness : 8/unsigned-integer
>> %% The following integers follow the above endianness
>> value1     : 32/integer
>> value2	   : 32/integer
>> ...
>> Because the endianness is specified in the bit syntax, such as   
>> unsigned-little-integer, it would be nice to encode the endianness  
>> in  a variable when I parse that byte, then use this variable to  
>> parse  the following integers in the packet header.  I would like  
>> to have  something like this:
>> if Endianness == 1 ->
>>    Spec = "32/little-integer";
>>     true ->
>>    Spec = "32/big-integer";
>> end,
>> <<Value1:Spec, Value2:Spec>> = Header,
>> However, putting a variable in the place of bit type specifier  
>> does  not seem to work.  I can't put a BIF, such as list_to_atom,  
>> there  either.
>> Any suggestions whether and how this might be done?
>
> The most straightforward method is something like this :)
>
>
>  if Endianness == 1 ->
>      <<Value1:32/little-integer, Value2:32/little-integer>> = Header;
>      true ->
>      <<Value1:32/big-integer, Value2:32/big-integer>> = Header;
>  end,
>
> :)
>
> In other hand you can construct string and then
> transform it to erlang code, see
> http://www.erlang.org/pipermail/erlang-questions/2005-April/ 
> 015274.html
>
> This will allow you construct fun before parsing data, and them  
> apply that fun on each packet.
>
>
> -- 
> Gaspar Chilingarov
>
> System Administrator,
> Network security consulting
>
> t +37493 419763 (mob)
> i 63174784
> e nm@REDACTED
> w http://zanazan.am/




More information about the erlang-questions mailing list