在C#中将Short [2]转换为Int32

Mat*_*atD 7 c# short int32 type-conversion

我在c#中有一个短数组,我需要在Int32中转换两个元素.我写的代码如下

uint pesoparz = (Convert.ToUInt16(values[0]));
Int32 pesotot = Convert.ToInt32(pesoparz *65536 + Convert.ToUInt16(values[1]));
Run Code Online (Sandbox Code Playgroud)

其中values []是短数组,pesotot是我想要获取的Int32.它工作但不幸的是当值[1]超过2 ^ 15时,我得到系统溢出异常.

为什么会发生异常?

Dmi*_*nko 5

您正在寻找unchecked哪个关闭IntegerOverflow:

  short left = -123;
  short right = -456;

  int result = unchecked(BitConverter.IsLittleEndian 
    ? (UInt16)left << 16 | (UInt16)right 
    : (UInt16)right << 16 | (UInt16)left);
Run Code Online (Sandbox Code Playgroud)

您可能希望使用来检测各部分组合成 的BitConverter.IsLittleEndian顺序。shortint


Rom*_*och 5

您可以使用按位运算符:

short[] parts = new short[2];
parts[0] = 1;
parts[1] = 2;

uint result = 0;

result = (ushort)parts[0] << 16 | (ushort)parts[1];
Run Code Online (Sandbox Code Playgroud)

结果将为0x00010002十六进制或65538十进制。