c# - writeline亂碼 - unity string utf 8
如何將UTF-8字節[]轉換為字符串? (8)
BitConverter
類可用於將byte[]
轉換為string
。
var convertedString = BitConverter.ToString(byteAttay);
BitConverter
類的文檔可以在MSDN
我有一個從我剛剛知道的文件中加載的byte[]
數組包含UTF-8 。 在一些調試代碼中,我需要將其轉換為字符串。 有沒有一個班輪可以做到這一點?
在封面下它應該只是一個分配和一個memcopy ,所以即使它沒有被實現,它也應該是可能的。
定義:
public static string ConvertByteToString(this byte[] source)
{
return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}
使用:
string result = input.ConvertByteToString();
嘗試這個:
string myresult = System.Text.Encoding.UTF8.GetString(byteArray);
將byte[]
轉換為string
似乎很簡單,但任何類型的編碼都可能會混淆輸出字符串。 這個小函數的工作原理沒有任何意外的結果:
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}
據我所知,沒有任何給定的答案保證了正確的行為與空終止。 直到有人以不同的方式顯示我,我用下面的方法編寫了我自己的靜態類來處理這個問題
// Mimics the functionality of strlen() in c/c++
// Needed because niether StringBuilder or Encoding.*.GetString() handle \0 well
static int StringLength(byte[] buffer, int startIndex = 0)
{
int strlen = 0;
while
(
(startIndex + strlen + 1) < buffer.Length // Make sure incrementing won't break any bounds
&& buffer[startIndex + strlen] != 0 // The typical null terimation check
)
{
++strlen;
}
return strlen;
}
// This is messy, but I haven't found a built-in way in c# that guarentees null termination
public static string ParseBytes(byte[] buffer, out int strlen, int startIndex = 0)
{
strlen = StringLength(buffer, startIndex);
byte[] c_str = new byte[strlen];
Array.Copy(buffer, startIndex, c_str, 0, strlen);
return Encoding.UTF8.GetString(c_str);
}
startIndex
的原因是在我正在處理的例子中,我需要將一個byte[]
解析為一個以空字符結尾的字符串數組。 在簡單情況下可以安全地忽略它
用於將從文件中讀取的字節數組byteArrFilename
轉換為純粹的ASCII格式的以零結尾的字符串的Linq byteArrFilename
將是這樣的:Handy用於讀取舊歸檔格式中的文件索引表等內容。
String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
.Select(x => x < 128 ? (Char)x : '?').ToArray());
我用'?'
作為任何不是純粹ascii的默認字符,但是當然可以改變。 如果你想確定你能檢測到它,只需使用'\0'
,因為TakeWhile
在開始時確保以這種方式構建的字符串不可能包含來自輸入源的'\0'
值。
這種轉換至少有四種不同的方式。
編碼的GetString
,但如果這些字節具有非ASCII字符,則無法返回原始字節。BitConverter.ToString
輸出是一個“ - ”分隔的字符串,但沒有.NET內置方法將字符串轉換回字節數組。Convert.ToBase64String
您可以使用Convert.FromBase64String
輕鬆地將輸出字符串轉換回字節數組。
注意:輸出字符串可能包含'+','/'和'='。 如果您想在URL中使用該字符串,則需要對其進行明確編碼。HttpServerUtility.UrlTokenEncode
您可以使用HttpServerUtility.UrlTokenDecode
輕鬆地將輸出字符串轉換回字節數組。 輸出字符串已經是URL友好的! 缺點是它需要System.Web
程序集,如果你的項目不是一個Web項目。
一個完整的例子:
byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters
string s1 = Encoding.UTF8.GetString(bytes); // ���
byte[] decBytes1 = Encoding.UTF8.GetBytes(s1); // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results
string s2 = BitConverter.ToString(bytes); // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
decBytes2[i] = Convert.ToByte(tempAry[i], 16);
// decBytes2 same as bytes
string s3 = Convert.ToBase64String(bytes); // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes
string s4 = HttpServerUtility.UrlTokenEncode(bytes); // gsjqFw2
byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4);
// decBytes4 same as bytes
還有類UnicodeEncoding,使用非常簡單:
ByteConverter = new UnicodeEncoding();
string stringDataForEncoding = "My Secret Data!";
byte[] dataEncoded = ByteConverter.GetBytes(stringDataForEncoding);
Console.WriteLine("Data after decoding: {0}", ByteConverter.GetString(dataEncoded));