2011-11-07 30 views
2

我試圖解析一個二進制文件,當它涉及到返回裝在小尾數爲16位數字,我希望這會工作:空二進制列表與模式匹配

foo(Bin, Bits) when is_binary(Bin) -> 
    <<A, B, C, D, _Rest>> = Bin, 
    (bar(<<A, B>>, Bits) =/= 0) and (bar(<<C, D>>, Bits) =/= 0). 

bar(<<N:16/little-unsigned-integer>>, Bits) -> 
    binary:at(Bits, N). 

不幸的是,當Bin爲4個字節或更少時,匹配器不工作。有沒有更好的方法使其餘的可以是空的?如果我可以避免在調用者中測試二進制長度,那麼效果會更好。

+0

如果輸入長度小於4個字節,什麼會匹配'C'或'D'? – sarnold

回答

1

你可以這樣做:

foo(<<A:16/little-unsigned-integer,B:16/little-unsigned-integer,_Rest/binary>>, Bits) -> 
    (binary:at(Bits, A) =/= 0) and (binary:at(Bits, B) =/= 0). 

這不會與二進制小於4個字節長的工作。在這種情況下應該發生什麼?

N.B. binary:at/2適用於二進制文件不是位串,偏移量以字節爲單位。

+0

感謝您的回覆。這是我需要讓我脫身的東西。在Erlang中使用二進制文件是非常有益的。該函數永遠不會被調用少於4個字節,所以這工作正常。 – Laurent