拆分二进制文件

时间:2012-06-15 15:24:40

标签: erlang

我试图从二进制字符串中拆分两个字段:

-define(S,<<"M\0\0\0522039355099,010100000008,0,010170000000,0,0,0,0,0,0,,,0,0,,‌​0110,00,150,0,0,0\0">>).<<Message_length:4/binary,Msg/binary>> = S.

前4个字节是以下消息的长度,另一个字节是消息,
空字节终止字符串。

结果是: **异常错误:o右手边值匹配
编辑 就在给定代码之前,有:

[Sequence|Reste] = binary:split(T,<<"\0">>),

“Reste”是否有界?

3 个答案:

答案 0 :(得分:4)

你的代码没问题,所以要么你没有二进制字符串,要么mystring的长度不符合模式。这是一个快速测试:

1> Mystring = <<"abcde">>.
<<"abcde">>
2> <<Message_length:4/binary,Msg/binary>> = Mystring.
<<"abcde">>
3> Message_length.
<<"abcd">>
4> Msg.
<<"e">>

如果您有一个字符串(整数列表)而不是二进制字符串(&lt;&lt;“string”&gt;&gt;),正如Vincenzo建议的那样,首先调用erlang:list_to_binary / 1。

希望有所帮助

编辑:我已经查看了Vincenzo的回答中留下的示例字符串。我已经尝试过你的代码,但仍然有效。到达那行代码时,Message_length和/或Msg是否已经绑定(并且与Mystring不同)?这会使模式匹配失败。

EDIT2:使用问题中的更新数据进行测试:

1> S = <<"M\0\0\0522039355099,010100000008,0,010170000000,0,0,0,0,0,0,,,0,0,,\342\200\214\342\200\2130110,00,150,0,0,0\0">>.
<<77,0,0,42,50,48,51,57,51,53,53,48,57,57,44,48,49,48,49,
  48,48,48,48,48,48,48,56,44,48,...>>
2> <<Message_length:4/binary,Msg/binary>> = S.
<<77,0,0,42,50,48,51,57,51,53,53,48,57,57,44,48,49,48,49,
  48,48,48,48,48,48,48,56,44,48,...>>
3> Message_length.
<<77,0,0,42>>
4> Msg.
<<"2039355099,010100000008,0,010170000000,0,0,0,0,0,0,,,0,0,,\342"...>>

答案 1 :(得分:1)

erlang字符串转义插值存在问题。第四个字节不作为"\0"进行插值,而是插入"\052"

1> Bin = <<"M\0\0\0522039355099,010100000008,0,010170000000,0,0,0,0,0,0,,,0,0,,0110,00,150,0,0,0\0">>.
<<77,0,0,42,50,48,51,57,51,53,53,48,57,57,44,48,49,48,49,                                                                                                                     
  48,48,48,48,48,48,48,56,44,48,...>>

所以你必须以这种方式写它。

2> f().
ok
3> Bin = <<"M\0\0\0","522039355099,010100000008,0,010170000000,0,0,0,0,0,0,,,0,0,,0110,00,150,0,0,0\0">>.
<<77,0,0,0,53,50,50,48,51,57,51,53,53,48,57,57,44,48,49,
  48,49,48,48,48,48,48,48,48,56,...>>

然后解析这种形式的消息的通常方法是:

4> <<L:32/little,Rest/binary>> = Bin.
<<77,0,0,0,53,50,50,48,51,57,51,53,53,48,57,57,44,48,49,
  48,49,48,48,48,48,48,48,48,56,...>>
5> L.
77
6> <<Msg:L/binary,R/binary>> = Rest.
<<"522039355099,010100000008,0,010170000000,0,0,0,0,0,0,,,0,0,,0110,00,150,0,0,0"...>>
7> R.
<<0>>
8> Msg.
<<"522039355099,010100000008,0,010170000000,0,0,0,0,0,0,,,0,0,,0110,00,150,0,0,0">>

答案 2 :(得分:0)

您必须在字符串上调用list_to_binary/1才能匹配。

如果您还有其他问题,请输入示例字符串!