如何连接Erlang中的两个二进制文件? [英] How do I concatenate two binaries in Erlang?

查看:187
本文介绍了如何连接Erlang中的两个二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,假设我有:

  B1 =< 1,2> ;. 
B2 =< 3,4>> ;.

如何连接B1和B2创建一个二进制B3,它是<< 1,2 ,3,4 >>?



我问这个的原因是因为我正在编写代码来对一些网络协议进行编码。我正在通过编写数据包中的字段的编码器来实现,我需要连接这些字段来构建整个数据包。



也许我这样做是错误的。应该将数据包建立为整数列表,并在最后一刻将列表转换为二进制文件?

解决方案

答案是不是gen_tcp:send将接受深层列表。所以,连接是简单的:

  B3 = [B1,B2]。 

这是O(1)。一般来说,当处理这种数据时总是建立深度的列表结构,并让io例程在输出结构中行走。唯一的复杂因素是任何中间例程都将接受深层次的列表。


How do I concatenate two binaries in Erlang?

For example, let's say I have:

B1 = <<1,2>>.
B2 = <<3,4>>.

How do I concatenate B1 and B2 to create a binary B3 which is <<1,2,3,4>>?

The reason I am asking this is because I am writing code to encode a packet for some networking protocol. I am implementing this by writing encoders for the fields in the packet and I need to concatenate those fields to build up the whole packet.

Maybe I am doing this the wrong way. Should I build up the packet as a list of integers and convert the list to a binary at the last moment?

解决方案

The answer is don't. gen_tcp:send will accept deep lists. So, concatenation is simply:

B3 = [B1, B2].

This is O(1). In general, when dealing with this sort of data always build up deep list structures and let the io routines walk the structure at output. The only complication is that any intermediate routines will have accept deep lists.

这篇关于如何连接Erlang中的两个二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆