Convert byte array to int32

I have a problem to convert byte array to int32 via BitConverter.ToInt32.

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: Destination array is not long enough to copy all the items in the > collection. Check array index and length

private void textBox2_TextChanged(object sender, EventArgs e)
{
    byte[] StrToByte = new byte[9];
    int IntHexValue;           
    StrToByte = Encoding.UTF8.GetBytes(textBox2.Text);
    textBox4.Text = BitConverter.ToString(StrToByte);
    IntHexValue = BitConverter.ToInt32(StrToByte, 0);
}
Jon Skeet
people
quotationmark

Presumably the UTF-8 representation of the text in textBox2 is fewer than 4 bytes long. BitConverter.ToInt32 requires 4 bytes of data to work with.

It's not clear what you're trying to achieve, by the way - but using BitConverter.ToInt32 on encoded text is rarely a useful thing to do.

Also, in terms of coding style:

  • You're allocating a new byte array, but then effectively ignoring it
  • You're declaring variables before you actually use them, for no reason. (Ideally declare variables at the point of first use)
  • Your variables don't follow .NET naming conventions, where they would be camelCased and ideally giving more of an indication of meaning rather than just the type

So even if your code were actually correct, it would be better written as:

private void textBox2_TextChanged(object sender, EventArgs e)
{
    byte[] encodedText = Encoding.UTF8.GetBytes(textBox2.Text);
    textBox4.Text = BitConverter.ToString(encodedText);
    int leadingInt32 = BitConverter.ToInt32(encodedText, 0);
    // Presumably use the value here...
}

(As I say, it's not clear what you're really trying to do, which is why the name leadingInt32 isn't ideal - if we knew the meaning you were trying to associate with the value, we could use that in the variable name.)

people

See more on this question at Stackoverflow