Elixir 二進(jìn)制數(shù)(和位串)

2023-12-14 16:56 更新

在Elixir中,你可以用<<>>來(lái)定義二進(jìn)制數(shù):

iex> <<0, 1, 2, 3>>
<<0, 1, 2, 3>>
iex> byte_size(<<0, 1, 2, 3>>)
4

一個(gè)二進(jìn)制數(shù)只不過(guò)是連續(xù)的字節(jié)。這些字節(jié)可以以任何形式組合,即使不形成一個(gè)合法的字符串:

iex> String.valid?(<<239, 191, 191>>)
false

字符串連接符實(shí)際上是二進(jìn)制數(shù)連接符:

iex> <<0, 1>> <> <<2, 3>>
<<0, 1, 2, 3>>

Elixir中有一個(gè)技巧是將字符串與空字節(jié)<<0>>相連接,以查看字符串內(nèi)部的二進(jìn)制數(shù):

iex> "he??o" <> <<0>>
<<104, 101, 197, 130, 197, 130, 111, 0>>

二進(jìn)制數(shù)中的每個(gè)數(shù)字代表一個(gè)字節(jié),因此上限是255.二進(jìn)制數(shù)允許修改存儲(chǔ)大小來(lái)存放大于255的數(shù),或?qū)⒋a點(diǎn)以u(píng)tf8格式表示:

iex> <<255>>
<<255>>
iex> <<256>> # truncated
<<0>>
iex> <<256 :: size(16)>> # use 16 bits (2 bytes) to store the number
<<1, 0>>
iex> <<256 :: utf8>> # the number is a code point
"ā"
iex> <<256 :: utf8, 0>>
<<196, 128, 0>>

如果一個(gè)字節(jié)有8位,那么將其傳送至1位空間會(huì)發(fā)生什么?

iex> <<1 :: size(1)>>
<<1::size(1)>>
iex> <<2 :: size(1)>> # truncated
<<0::size(1)>>
iex> is_binary(<< 1 :: size(1)>>)
false
iex> is_bitstring(<< 1 :: size(1)>>)
true
iex> bit_size(<< 1 :: size(1)>>)
1

其值不再是二進(jìn)制數(shù),而是位串——只是一串位!所以一個(gè)二進(jìn)制數(shù)是一個(gè)位數(shù)為8的倍數(shù)的位串。

我們也可以對(duì)二進(jìn)制數(shù)與位串進(jìn)行模式匹配:

iex> <<0, 1, x>> = <<0, 1, 2>>
<<0, 1, 2>>
iex> x
2
iex> <<0, 1, x>> = <<0, 1, 2, 3>>
** (MatchError) no match of right hand side value: <<0, 1, 2, 3>>

注意二進(jìn)制數(shù)匹配中的每個(gè)入口都期望匹配到8bit。如果我們想要匹配一個(gè)未知大小的二進(jìn)制數(shù),可以在模式的結(jié)尾使用二進(jìn)制數(shù)修改器:

iex> <<0, 1, x :: binary>> = <<0, 1, 2, 3>>
<<0, 1, 2, 3>>
iex> x
<<2, 3>>

可以用字符串連接符達(dá)到類似的效果:

iex> "he" <> rest = "hello"
"hello"
iex> rest
"llo"

關(guān)于二進(jìn)制數(shù)/位串構(gòu)造符<<>>的完整介紹可以在Elixir文檔中找到??偨Y(jié)一下位串,二進(jìn)制數(shù)和字符串。一個(gè)字符串是一個(gè)以UTF-8格式編碼的二進(jìn)制數(shù),而一個(gè)二進(jìn)制數(shù)是一個(gè)位數(shù)為8的倍數(shù)的位串。盡管我們展示了Elixir處理bit位和字節(jié)的靈活性,但99%的時(shí)間你都在和二進(jìn)制數(shù)打交道,并且使用is_binary/1byte_size/1函數(shù)。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)