Elixir中的String、binaries和bitstring

http://elixir-lang.github.io/getting-started/binaries-strings-and-char-lists.html

https://elixirforum.com/t/bitstring-and-binary/2351/4

字符串是怎么保存到计算机中的

iex>?a
97
iex>?吴
21556

a的code point是97,也就是110 0001;吴的code point是21556,也就是101 0100 0011 0100。这是unicode标准规定的。

但是计算机中,我们是以byte为单位来存放的,那么110 0001只需要一个字节,填满8位就是0110 0001;101 0100 0011 0100需要两个字节,填满16位就是0101 0100 0011 0100。这个过程就是所谓的utf-8编码过程。

他们之间的关系

A bitstring is a type that stores arbitrary number of bits, you can have a 5bit bitstring whereas binary stores arbitrary number of bytes

Here is some code that should make things clearer:

# bitstring
bs = << 3 :: size(2) >>      # => 2 bits 11
IO.inspect bs                # => <<3::size(2)>>
IO.inspect is_bitstring(bs)  # => true
IO.inspect is_binary(bs)     # => false

# binary
bin = << 3 >>                # => 8 bits or 1 byte
IO.inspect bin               # => <<3>>
IO.inspect is_bitstring(bin) # => true
IO.inspect is_binary(bin)    # => true

A binary is just a collection of bytes, so it has to have a number of bits that is divisible by 8 (i.e. a byte). So you can have a 8 bit binary, 16 bit binary and so on. If your binary is not divisible by 8, e.g. 7bits, 15bits, 14 bits, 23bits, you have a bitstring. And since a bitstring can have any number of bits even a binary is a bitstring. However, the inverse is not true.

杀手图来了

So a subset of bitstrings are binaries, and a subset of binaries are strings. Like this:

04165405_Ndqz.png

转载于:https://my.oschina.net/u/855913/blog/1614208

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值