我有以下问题:如果String
包含char
未知的ASCII
,它将使用63。
因此,我将编码更改为UTF8
,但是我知道char
可以具有两个length
的bytes
,所以出现了超出范围的错误。
我该如何解决这个问题?
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] baInput = enc.GetBytes(strInput);
// Split byte array (6 Byte) in date (days) and time (ms) parts
byte[] baMsec = new byte[4];
byte[] baDays = new byte[2];
for (int i = 0; i < baInput.Length; i++)
{
if (4 > i)
{
baMsec[i] = baInput[i];
}
else
{
baDays[i - 4] = baInput[i];
}
}
最佳答案
您似乎遇到的问题是,使用UTF8时您知道字符数,但不知道字节数。要解决该问题,您可以使用:
byte[] baMsec = Encoding.UTF8.GetBytes(strInput.SubString(0, 4));
byte[] baDays = Encoding.UTF8.GetBytes(strInput.SubString(4));
关于c# - C#utf8编码字节数组超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38047514/