# [筆記] Base64 表示法
### :question: **疑問**
1. **What** is Base64 ?
2. **How** to use Base64 ?
3. **Why** uses Base64 ?
:::success
:bulb: **快速解答**
1. Base64 是用來表達二進位 (1、0) 的一種表達方式。
2. 將 Byte[ ] 型別資料,使用語言內建函式進行轉換。
3. 使用字串的方式傳送並縮短傳送的資料長度。
:::
---
### 1. 什麼是 Base64
#### (1) 了解 Base64 之前,先了解什麼是 ... Byte
- 電腦記憶體的**計量單位**:**Byte**,由 8 個 Bit 所組成
- 每個 Byte 用數字來表示的話,可以由 0 => 255,共256
- 如果有很多 **Bytes**,其實可以用 **Byte[ ] 型別**表示
- 例如:Byte[ 3 ]=[ 255 , 1 , 2] 類似於 [ 11111111 , 00000001 , 00000010]
- 但是:如果有很多 Bytes,用 Byte[ ] 表達也是有點麻煩
- 數字是一種將 (1、0) 轉譯 (Encoding) 的方法,將**二進位轉換成十進位**
#### (2) 有十進位,就有64進位的 Encoding 方法
- Base64 使用 [ A-Z ]、[ a-z ]、[ 0-9 ] 加上 "+"、"\\"、"=",**共 65 種符號**作為編碼
- 因為是 64 進位,所以是採用 6 個 Bits 當作一組單位進行轉譯
- 例如:[ 01001101 , 01100001 , 01101110]
- 可以重新拆解成:[ 010011 , 010110 , 000101 , 101110]
- 等同於 Base64 上的:[ 19 , 22 , 5 , 46]
- 這樣就可以透過 Base64 轉譯成:"TWFu" 字串
---
### 2. 如何使用 Base64
- 以 **C# 語言**為例:
- 可以使用 **Convert.ToBase64String()** 方法
- 但是該方法需要放入 **Byte[ ] 型別**的變數
```csharp=1
string message = "Man";
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(message);
byte[] byteArrayInput={77,97,110}; // 自行輸入
for(int i=0;i<byteArray.Length;i++)
{
Console.WriteLine(byteArray[i]); // 依序印出:77,97,110
Console.WriteLine(byteArrayInput[i]); // 依序印出:77,97,110
}
string base64String = Convert.ToBase64String(byteArray);
string base64StringInput = Convert.ToBase64String(byteArrayInput);
Console.WriteLine("Base64 Encoded String of byteArray: " + base64String); // 印出:TWFu
Console.WriteLine("Base64 Encoded String of byteArrayInput: " + base64StringInput); // 印出:TWFu
```
```mermaid
graph
string變數 --轉換成Byte[]--> 作為Convert.ToBase64String方法的參數 --> 轉譯成Base64字串
```
---
### 3. 為什麼要使用 Base64
#### (1) 太多101010,減少傳送的訊息量
#### (2) 避免特殊的字元被解讀錯誤,統一轉換成 Base64 進行網路傳送
- 例如:Non-HTTP-compatible characters
#### (3) 如果應用程式不支援陣列傳送與接收,可以使用 Base64 進行 string 傳送
#### (4) 避免明碼直接傳送,轉換成不容易解讀的代碼傳送
---
:::info
:bookmark_tabs: **參考資料**
>Wiki Base64:<https://zh.wikipedia.org/zh-tw/Base64>
>Wiki ASCII:<https://zh.wikipedia.org/zh-tw/ASCII>
>stackoverflow 1:https://stackoverflow.com/questions/3538021/why-do-we-use-base64
>stackoverflow 2:https://stackoverflow.com/questions/4070693/what-is-the-purpose-of-base-64-encoding-and-why-it-used-in-http-basic-authentica
:::