### 用途 > 非ASCII字符的傳輸及儲存 (通常是二進位資料) > 解決各系統/傳輸協議二進制資料不兼容的問題 * 二進位資料/特殊字元 的處理在不同機器/協議上不一定通用 * 某些 Protocal 只支援純文本 (ex: http 的 URL) * 圖片、音檔等二進位資料經base64編碼後可以文本傳輸 (JSON、XML) * 可應用於 DataURI,減少 http(s) 請求 ``` data:[<mediatype>][;base64],<data> ``` ``` data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH hhx4dbgYKAAA7 ``` --- ### 64 的意義 ? > **64 (2^6^)** 種可見的 **ASCII** 字符 * `A-Z` (26) * `a-z` (26) * `0-9` (10) * `+` `/` (2) ``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ``` --- ### 如何轉換 ? 1. 將資料由 ASCII 轉為 `8 bits` 2 進制,每 `3 bytes (24 bits)` 一組 2. 若資料不足 3 bytes,則右側以 `0` 補位 3. 每組 `6 bits` 為單位,對應 Base64 Table,共 `4` 個字符 4. 6 bits 皆為補位者,由 `=` 表示  --- ### 範例 > 1. 將資料由 ASCII 轉為 `8 bits` 2 進制,每 `3 bytes (24 bits)` 一組 > 2. 若資料不足 3 bytes,則右側以 `0` 補位 * `B(66)` : 0 1 0 0 0 0 1 0 * `C(67)` : 0 1 0 0 0 0 1 1 ==補成 3 bytes== : 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 ~~0 0 0 0 0 0 0 0~~ --- > 3. 每組 `6 bits` 為單位,對應 Base64 Table,共 `4` 個字符 > 4. 6 bits 皆為補位者,由 `=` 表示 ==6 bits 一組== : 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 0 0 ~~0 0 0 0 0 0~~ * `Q(16)` : 0 1 0 0 0 0 * `k(36)` : 1 0 0 1 0 0 * `M(24)` : 0 0 1 1 0 0 * `=` : ~~0 0 0 0 0 0~~ **轉換結果 : `BC` -> `QkM=`** --- ### 數據膨脹問題 每 `3 bytes` 的資料轉為 `4` 個字符 -> `4 bytes` > 4 / 3 := 1.33, 約膨脹 33 % --- ### 參考資料 * [为什么要使用base64编码,有哪些情景需求?](https://www.zhihu.com/question/36306744) * [Base64編碼是什麼?](https://matthung0807.blogspot.com/2022/06/what-is-base64-encode.html) * [【深入淺出】Base編碼 (Base64為例子)](https://isdaniel.github.io/base64-principle/) * [淺談 Base64 與應用實例分享](https://blog.errorbaker.tw/posts/cian/base64-qrcode/#data-uris)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up