Bitstrings and Binaries 的不同

来源:互联网 发布:哪里有淘宝买家数据? 编辑:程序博客网 时间:2024/06/10 15:50

Bitstrings and Binaries (Erlang bit syntax minihowto part 2)

What’s the difference between the Binary and Bitstring types in Erlang? Well, abitstring is a sequence of bits of any length; a binary is a sequence of bits where the number of bits is evenly divisible by 8. (So any binary is also a bitstring.)

Some examples:

1> <<2#11110000:5>>.< <16:6>>2> <<2#11110000:6>>.< <48:6>>3> erlang:is_bitstring(<<2#11110000:6>>).true4> erlang:is_binary(<<2#11110000:6>>).false5> erlang:is_bitstring(<<2#11110000:8>>).true6> erlang:is_binary(<<2#11110000:8>>).true

In the Erlang bit syntax there are 2 clarifying (?) type synonyms:

bytes == binarybits  == bitstring

which are basically telling you to think of binaries as sequence of bytes, and bitstrings as sequence of bits. Quite obvious right? Well, it wasn’t for me at first.

It’s also worth noting how binaries and bitstrings are converted into text strings. Given the binary<<16#50>> storing the letter ‘P’,

7> <<16#50>><<"P">>8>erlang:bitstring_to_list(<<16#50>>). #I could've used binary_to_list()"P"          %great!9>erlang:bitstring_to_list(<<16#50:5>>).[<<16:5>>]  %mmh...

The result of command #9 is not exactly what I had imagined. Yes, it’s a list, but it’s certainly not a text string, and I was expecting a text string. Why was I expecting a text string if the API is namedbitstring_to_list() ? Because if I was in the middle of coding a text manipulation algorithm and calledbitstring_to_list(), I would probably (wrongly) assume that it would do some magic and transformany bitstring in a usable text string. Why? Because we are used to treat text strings as lists. Why? Because we don’t have APIs that mention “strings”: all the builtin APIs only mention lists. That’s the problem. We are using a list API as if it was a string API, when a generic list is not necessarily a string.

0 0
原创粉丝点击