[C#]RBK(8進制)和字串互轉

因特殊需求,需要實作該功能,主要功能的轉換是類似以下範例:
     "\304\343\272\303" => "你好"

不廢話,附上程式碼。

// 中文轉Rbk8進制
private void button1_Click(object sender, EventArgs e)
{
    string hz = this.richTextBox1.Text;
    byte[] gbk = Encoding.GetEncoding("GBK").GetBytes(hz);
    string s1 = "";
    foreach (byte b in gbk)
    {
        s1 += $"\\{Convert.ToString(b, 8)}";
    }
    this.richTextBox2.Text = s1;
}


// Rbk8進制轉中文
private void button2_Click(object sender, EventArgs e)
{
    string cd = this.richTextBox1.Text;
    string[] b4 = RemoveEmptyString(cd.Split('\\'));
    byte[] bs = new byte[b4.Length];
    for (int i = 0; i < b4.Length; i++)
    {
        bs[i] = (byte)Convert.ToByte(b4[i], 8);
    }
    this.richTextBox2.Text = Encoding.GetEncoding("GBK").GetString(bs);
}

// 移除空字串
private string[] RemoveEmptyString(string[] strArr)
{
    List strList = new List(); ;
    foreach (var item in strArr)
    {
        if (!string.IsNullOrWhiteSpace(item))
        {
            strList.Add(item);
        }
    }
    return strList.ToArray();
}

留言

這個網誌中的熱門文章

[C#] 無法載入檔案或組件 或其相依性的其中之一。 找到的組件資訊清單定義與組件參考不符。 (發生例外狀況於 HRESULT: 0x80131040)

[Cloud CICD] 後端篇 - .Net8 WebApi, Github Action, Azure App Service

[Cloud CICD] 前端篇 - Vue3, Github Action, Azure Static Web App