簡體   English   中英

C# - 將 UTF8 字符串轉換為位、修改位並轉換回 UTF8 字符串

[英]C# - Convert UTF8 String into bits, modify bits, and convert back into UTF8 String

對於我正在處理的項目,我需要能夠將 UTF8 字符串轉換為位或字節以進行修改和返回。 (位/字節類型無關緊要.. '138' 或 '00000001' 或 '0A' - 只要我能夠將其修改為字符串並將字節轉換回字符串)

我嘗試了幾件事,但沒有任何效果。 在大多數情況下,我一直在嘗試獲取File.ReadAllBytes(path)的結果並將字節轉換為可修改的字符串並返回,但沒有任何成功。 還嘗試使用測試字符串到BitArray中做同樣的事情,但沒有更好的運氣。

這是我在一個更好的例子中嘗試做的事情(偽代碼)

string input = "ABC";

Byte[] bytes = StringToBytes(input);
Byte[] bytes2;

string bytestring;
foreach (Byte byte in bytes) {
    bytestring = byte.ToString();
    /// modify bytestring to the value of a different byte here ///
    bytes2.Add(bytestring.ToByte());
}

return BytesToString(bytes2);

返回: 'ACD' (或其他)

如果您嘗試將文件讀入 byte[] 數組,修改這些字節並將其轉換回字符串,則可以執行以下操作:

// read the file into a byte array
var bytes = File.ReadAllBytes(inputFileName);

// modify the bytes

// now convert back to a UTF string
var stringFromByteArray = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM