Erlang中的Binary和Bitstring有什么区别? [英] What is the difference between a Binary and a Bitstring in Erlang?

查看:262
本文介绍了Erlang中的Binary和Bitstring有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Erlang shell中,我可以执行以下操作:

In the Erlang shell, I can do the following:

A = 300.
    300
<<A:32>>.
    <<0, 0, 1, 44>>

但是当我尝试以下操作时:

But when I try the following:

B = term_to_binary({300}).
    <<131,104,1,98,0,0,1,44>>
<<B:32>>
    ** exception error: bad argument
<<B:64>>
    ** exception error: bad argument

在第一种情况下,我使用一个整数,并使用位串语法将其放入32位字段中.那按预期工作.在第二种情况下,我使用term_to_binary BIF将元组转换为二进制,然后尝试使用bitstring语法从中解压缩某些位.为什么第一个示例有效,但是第二个示例失败?看起来他们俩都在做非常相似的事情.

In the first case, I'm taking an integer and using the bitstring syntax to put it into a 32-bit field. That works as expected. In the second case, I'm using the term_to_binary BIF to turn the tuple into a binary, from which I attempt to unpack certain bits using the bitstring syntax. Why does the first example work, but the second example fail? It seems like they're both doing very similar things.

推荐答案

二进制文件和位字符串之间的区别是二进制文件的长度可以被8整除,即它不包含部分"字节;位串没有这种限制.

The difference between in a binary and a bitstring is that the length of a binary is evenly divisible by 8, i.e. it contains no 'partial' bytes; a bitstring has no such restriction.

这种区别在这里不是你的问题.

This difference is not your problem here.

您面临的问题是语法错误.如果您想从二进制文件中提取前32位,则需要编写一个完整的匹配语句-像这样:

The problem you're facing is that your syntax is wrong. If you would like to extract the first 32 bits from the binary, you need to write a complete matching statement - something like this:

<<B1:32, _/binary>> = B.

请注意,/binary很重要,因为它将匹配二进制数的剩余部分,而不管其长度如何.如果省略,则匹配的长度默认为8(即1个字节).

Note that the /binary is important, as it will match the remnant of the binary regardless of its length. If omitted, the matched length defaults to 8 (i.e. one byte).

您可以在《 Erlang参考手册》中有关位语法的部分中了解有关二进制文件以及如何使用二进制文件的更多信息. a>.

You can read more about binaries and working with them in the Erlang Reference Manual's section on bit syntax.

编辑

在您的评论中,<<A:32>>不仅仅用于整数,还用于.通过我给出的链接,位语法使您可以指定二进制匹配的许多方面,包括绑定变量的数据类型-虽然默认类型为integer,但您也可以说floatbinary(还有其他) . :32部分表示匹配需要32位-根据您的数据类型,这可能有意义,也可能没有意义,但这并不意味着它仅对整数有效.例如,您可以说<<Bits:10/bitstring>>来描述一个10位的位串.希望有帮助!

To your comment, <<A:32>> isn't just for integers, it's for values. Per the link I gave, the bit syntax allows you to specify many aspects of binary matching, including data types of bound variables - while the default type is integer, you can also say float or binary (among others). The :32 part indicates that 32 bits are required for a match - that may or may not be meaningful depending on your data type, but that doesn't mean it's only valid for integers. You could, for example, say <<Bits:10/bitstring>> to describe a 10-bit bitstring. Hope that helps!

这篇关于Erlang中的Binary和Bitstring有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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