Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Short[2] to Int32 in C#

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?

like image 669
MatD Avatar asked Jan 11 '17 14:01

MatD


People also ask

How do you use Convert to int 32?

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.

How do you convert short to int in C++?

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.

What does convert to Int32 mean?

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)


1 Answers

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.

like image 101
Roman Doskoch Avatar answered Sep 30 '22 10:09

Roman Doskoch