2012-07-20 85 views
2

我正在使用BitConverter.ToInt32将一个Byte数组转换为int。BitConverter.ToInt32转换2个字节

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

什么是最快的方法。

谢谢。

回答

2

您应该改为使用(int)BitConverter.ToInt16(..)ToInt16被设置为将两个字节读入short。然后,您只需将其转换为带有演员表的int即可。

+1

但是可能想要记录关于endianess。 – 2012-07-20 02:47:49

1

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通话(字节[])似乎是一个更好的主意,那么就保存到一个int:

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

记住尽管如此。在小端机上,{ 0x00 0x02 }实际上是512,而不是2(0x0002仍然是2,而不管字节顺序)。

1

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

short可以隐式转换为int