BitConverter.ToInt32 to convert 2 bytes

前端 未结 3 471
执念已碎
执念已碎 2021-01-15 06:32

I am using BitConverter.ToInt32 to convert a Byte array into int.

I have only two bytes [0][26], but the function needs 4 bytes, so I have to add two 0 bytes to the

3条回答
  •  一向
    一向 (楼主)
    2021-01-15 06:51

    Array.Copy. Here is some code:

    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
    

    However, a call to `BitConverter.ToInt16(byte[]) seems like a better idea, then just save it to an int:

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

    Keep in mind endianess however. On little endian machines, { 0x00 0x02 } is actually 512, not 2 (0x0002 is still 2, regardless of endianness).

提交回复
热议问题