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);
}
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:
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.)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With