Search code examples
c#encodingarraysutf8-decode

C# utf8-encoding bytearray out of range


I have the following problem: if the String contains a char that is not known from ASCII, it uses a 63.

Because of that i changed the encoding to UTF8, but I know a char can have the length of two bytes, so I get a out of range error.
How can I solve the problem?

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];
    }
}

Solution

  • The problem you seem to be having is that you know the number of characters, but not the number of bytes, when using UTF8. To solve just that problem, you could use:

    byte[] baMsec = Encoding.UTF8.GetBytes(strInput.SubString(0, 4));
    byte[] baDays = Encoding.UTF8.GetBytes(strInput.SubString(4));