I have a short array in c# and I need to convert two elements in an Int32. The code I wrote is the following
uint pesoparz = (Convert.ToUInt16(values[0]));
Int32 pesotot = Convert.ToInt32(pesoparz *65536 + Convert.ToUInt16(values[1]));
where values[] is the short array and pesotot is the Int32 that I would like to obtain. It works but unfortunately when the value[1] exceeds 2^15, I get the system overflow exception.
Why does the exception occur?
Syntax: public static int ToInt32 (decimal value); Here, the value is the decimal number which is to be converted. Return Value: It returns a 32-bit signed integer equivalent to the specified value. Exception: This method will give OverflowException if the specified value is less than MinValue or greater than MaxValue.
short a=2000; int b; b=a; Here, the value of a is promoted from short to int without the need of any explicit operator. This is known as a standard conversion.
ToInt32(UInt32) Converts the value of the specified 32-bit unsigned integer to an equivalent 32-bit signed integer. ToInt32(Single) Converts the value of the specified single-precision floating-point number to an equivalent 32-bit signed integer. ToInt32(Object, IFormatProvider)
You can use bitwise operators:
short[] parts = new short[2];
parts[0] = 1;
parts[1] = 2;
uint result = 0;
result = (ushort)parts[0] << 16 | (ushort)parts[1];
The result will be 0x00010002
in hex or 65538
in decimal.
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