How to convert an int to a little endian byte array?

后端 未结 8 759
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 08:00

I have this function in C# to convert a little endian byte array to an integer number:

int LE2INT(byte[] data)
{
  return (data[3] << 24) | (data[2] &l         


        
相关标签:
8条回答
  • 2020-12-09 08:52

    Could you use the BitConverter class? It will only work on little-endian hardware I believe, but it should handle most of the heavy lifting for you.

    The following is a contrived example that illustrates the use of the class:

    if (BitConverter.IsLittleEndian)
    {
        int someInteger = 100;
        byte[] bytes = BitConverter.GetBytes(someInteger);
        int convertedFromBytes = BitConverter.ToInt32(bytes, 0);
    }
    
    0 讨论(0)
  • 2020-12-09 08:56

    Just reverse it, Note that this this code (like the other) works only on a little Endian machine. (edit - that was wrong, since this code returns LE by definition)

      byte[] INT2LE(int data)
      {
         byte[] b = new byte[4];
         b[0] = (byte)data;
         b[1] = (byte)(((uint)data >> 8) & 0xFF);
         b[2] = (byte)(((uint)data >> 16) & 0xFF);
         b[3] = (byte)(((uint)data >> 24) & 0xFF);
         return b;
      }
    
    0 讨论(0)
提交回复
热议问题