二進

二進位 在 Elixir

7 個練習

關於 二進位

  • binary 型別是 bitstring 型別的特化。
  • binary 由位元組組成。
    • 位元組是 8 個位元。
    • 位元組可以表示從0到255的數字。
    • 處理位元組時,經常會用到十六進位整數值:0x00到0xFF。
  • binary 字面值使用 <<>> 特殊形式定義。
    • 如果位元組使用大於255的整數,只會取用最後 8 個位元,除非你用 ::運算子指定要使用的單位和/或大小。
  • <>/2可以用來串接 bitstring、binary 和字串。
<<255>> == <<0xFF>>
# Overflowing bits are truncated
<<256>> == <<0>>
<<256::size(16)>> == <<1, 0>>

<<"Hello">> == <<72, 101, 108, 108, 111>>

null-byte 是<<0>>的另一個名稱。

字串是編碼過的 binary 資料

  • 字串是以 UTF-8 格式編碼的 binary 資料。
    • 它們以 8 位元(一個位元組)為單位編碼,最多用 4 個位元組來表示超過 255 個字元。
    • 字串的長度不一定和它的位元組大小相同。
# This string has a string length of 5, but is made up of 7 bytes
string = "cześć"
String.length(string) != byte_size(string)

# Even emoji strings are encoded binaries
"👍" == <<240, 159, 145, 141>>

對 binary 資料進行模式比對

# Ignore the first 8 bytes, bind the remaining variable sized binary to `body`
<<_::binary-size(8), body::binary>>

字串也可以這樣做:

# bind the first 5 bytes to `name`,
# match the string literal " the ",
# bind remaining bytes to `species`
<<name::binary-size(5), " the ", species::binary>> = <<"Frank the Walrus">>
{name, species}
# => {"Frank", "Walrus"}
透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 二進位

練習已鎖定

再解鎖 1 個練習,就能練習 二進位