BitConverter.ToInt32 to convert 2 bytes

前端 未结 3 468
执念已碎
执念已碎 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:50

    You should probably do (int)BitConverter.ToInt16(..) instead. ToInt16 is made to read two bytes into a short. Then you simply convert that to an int with the cast.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-15 06:58

    You should call `BitConverter.ToInt16, which only reads two bytes.

    short is implicitly convertible to int.

    0 讨论(0)
提交回复
热议问题