2

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

-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">>),

“休息”有界吗?

4

3 回答 3

4

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

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

如果您有一个字符串(整数列表)而不是二进制字符串(<<"string">>),正如 Vincenzo 建议的那样,请先调用 erlang:list_to_binary/1 。

希望能帮助到你

编辑:我已经检查了您在文森佐的回答的评论中留下的示例字符串。我已经用你的代码试过了,仍然有效。到达那行代码时,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"...>>
于 2012-06-15T15:33:49.140 回答
1

erlang 字符串转义插值存在问题。第四个字节不插值为"\0"but "\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">>
于 2012-06-15T22:43:20.383 回答
0

您必须调用list_to_binary/1要匹配的字符串。

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

于 2012-06-15T15:31:19.530 回答