Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte array to int32

Tags:

c#

winforms

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);
}
like image 532
user2955372 Avatar asked Nov 05 '13 07:11

user2955372


2 Answers

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.)

like image 89
Jon Skeet Avatar answered Sep 30 '22 19:09

Jon Skeet


Reason of this error is that BitConverter.ToInt32 expects byte array of at least 4 elements, but you pass to it result of Encoding.UTF8.GetBytes(textBox2.Text), which can be less than 4 bytes if user typed something short to your textBox2, for example "123" - it will be only 3 bytes. As a workaround for your scenario you should pad byte array to at least 4 bytes long, something like this:

    StrToByte = Encoding.UTF8.GetBytes("123");

    if (StrToByte.Length < 4)
    {
        byte[] temp = new byte[4];
        StrToByte.CopyTo(temp, 0);
        StrToByte = temp;
    }

    IntHexValue = BitConverter.ToInt32(StrToByte, 0);
like image 20
SergeyS Avatar answered Sep 30 '22 20:09

SergeyS