BitConverter.ToInt32转换2个字节

我正在使用BitConverter.ToInt32将Byte数组转换为int。

我只有两个字节[0] [26],但该函数需要4个字节,所以我必须在现有字节的前面添加两个0字节。

什么是最快的方法。

谢谢。

你应该做(int)BitConverter.ToInt16(..)而不是。 ToInt16用于将两个字节读入short 。 然后你只需使用强制转换将其转换为int

你应该调用`BitConverter.ToInt16,它只读取两个字节。

short可以隐式转换为int

Array.Copy 。 这是一些代码:

 byte[] arr = new byte[] { 0x12, 0x34 }; byte[] done = new byte[4]; Array.Copy(arr, 0, done, 2, 2); // http://msdn.microsoft.com/en-us/library/z50k9bft.aspx int myInt = BitConverter.ToInt32(done); // 0x00000026 

但是,调用`BitConverter.ToInt16(byte [])似乎是一个更好的主意,然后将其保存到int:

 int myInt = BitConverter.ToInt16(...); 

但请记住endianess。 在小端机器上, { 0x00 0x02 }实际上是512,而不是2( 0x0002仍然是2,无论字节顺序如何)。