我只知道list_to_binary在 erlang otp 中,但今天我看到了iolist_to_binary?
我在 erlang shell 中尝试过,但我找不到区别。
(ppb1_bs6@esekilvxen263)59> list_to_binary([<<1>>, [1]]).
<<1,1>>
(ppb1_bs6@esekilvxen263)60> iolist_to_binary([<<1>>, [1]]).
<<1,1>>
(ppb1_bs6@esekilvxen263)61> iolist_to_binary([<<1>>, [1], 1999]).
** exception error: bad argument
in function iolist_to_binary/1
called as iolist_to_binary([<<1>>,[1],1999])
(ppb1_bs6@esekilvxen263)62> list_to_binary([<<1>>, [1], 1999]).
** exception error: bad argument
in function list_to_binary/1
called as list_to_binary([<<1>>,[1],1999])
(ppb1_bs6@esekilvxen263)63> list_to_binary([<<1>>, [1], <<1999>>]).
<<1,1,207>>
(ppb1_bs6@esekilvxen263)64> ioslist_to_binary([<<1>>, [1], <<1999>>]).
** exception error: undefined shell command ioslist_to_binary/1
(ppb1_bs6@esekilvxen263)65> iolist_to_binary([<<1>>, [1], <<1999>>]).
<<1,1,207>>
Run Code Online (Sandbox Code Playgroud)
从测试来看,我觉得iolist_to_binary可能和list_to_binary.
在当前版本的 Erlang/OTP 中,这两个函数都会自动展平您提供的列表或 iolist(),在功能上只留下一个区别,即 list_to_binary/1 不接受二进制参数,但 iolist_to_binary/1 将:
1> erlang:iolist_to_binary(<<1,2,3>>).
<<1,2,3>>
2> erlang:list_to_binary(<<1,2,3>>).
** exception error: bad argument
in function list_to_binary/1
called as list_to_binary(<<1,2,3>>)
Run Code Online (Sandbox Code Playgroud)
这从 iolist() 的类型规范中可以清楚地看出:
maybe_improper_list(byte() | binary() | iolist(), binary() | [])
Run Code Online (Sandbox Code Playgroud)
如您所见,iolist() 可以是二进制文件,但显然列表永远不能是二进制文件。
如果您想了解不正确列表类型的卷积,您可以在(Erlang) Types and Function Specifications找到它的定义以及 iolist() 。
就实际使用而言,iolist() 是一个凌乱或未展平的列表。将其视为一种懒惰的输出,生产者故意不将其展平为适当的列表作为优化,因为并非每个消费者都需要展平它。您可以通过检查 io_lib:format/2 的输出来查看它的样子:
1> io_lib:format("Hello ~s ~b!~n", ["world", 834]).
[72,101,108,108,111,32,"world",32,"834",33,"\n"]
Run Code Online (Sandbox Code Playgroud)
或者:
2> io:format("~w~n", [ io_lib:format("Hello ~s ~b!~n", ["world", 834]) ]).
[72,101,108,108,111,32,[119,111,114,108,100],32,[56,51,52],33,[10]]
Run Code Online (Sandbox Code Playgroud)
我注意到您的许多示例都包含数字 1999。顺便说一下,尝试将包含任何大于 255 的任何数字的任何列表或 iolist() 转换为二进制文件总是会失败:
8> erlang:list_to_binary([1,2,3,255]).
<<1,2,3,255>>
9> erlang:list_to_binary([1,2,3,256]).
** exception error: bad argument
in function list_to_binary/1
called as list_to_binary([1,2,3,256])
Run Code Online (Sandbox Code Playgroud)
这是因为它想从您的列表中创建一个字节列表,而 255 以上的数字在其可能的字节表示方面是不明确的;无法知道您的意思是小端还是大端等(请参阅(维基百科)端序)。
小智 0
iolist_to_binary- 将 iolist 转换为二进制
供您参考: http://www.erlangpatterns.org/iolist.html http://www.erlang.org/doc/man/erlang.html