开发者

Converting little endian to int

开发者 https://www.devze.com 2022-12-10 01:09 出处:网络
First of all, I think this question is not C# independent. But can also be used in other languages like C.

First of all, I think this question is not C# independent. But can also be used in other languages like C.


I'm now trying to parse a file format which stores integers in 4 bytes little-endian format. TBH, I don't know how the lit开发者_JAVA技巧tle-endian format nor big-endian format works.

But I need to convert them into an usable int variable.

For example, 02 00 00 00 = 2

So far, I have this code to convert the first 2 bytes: (I used FileStream.Read to store the raw datas into a buffer variable)

        int num = ((buffer[5] << 8) + buffer[4]);

But it will only convert the first two bytes. (02 00 in the example, not 02 00 00 00)

Any kind of help would be appreciated :)


int GetBigEndianIntegerFromByteArray(byte[] data, int startIndex) {
    return (data[startIndex] << 24)
         | (data[startIndex + 1] << 16)
         | (data[startIndex + 2] << 8)
         | data[startIndex + 3];
}

int GetLittleEndianIntegerFromByteArray(byte[] data, int startIndex) {
    return (data[startIndex + 3] << 24)
         | (data[startIndex + 2] << 16)
         | (data[startIndex + 1] << 8)
         | data[startIndex];
}


Using built-in methods:

byte[] data = { 2, 0, 0, 0 };
Array.Reverse(data);
int value = BitConverter.ToInt32(data, 0);

On the other side of the spectrum, using optimised unsafe code:

public static unsafe void SwapInts(int[] data) {
  int cnt = data.Length;
  fixed (int* d = data) {
    byte* p = (byte*)d;
    while (cnt-- > 0) {
      byte a = *p;
      p++;
      byte b = *p;
      *p = *(p + 1);
      p++;
      *p = b;
      p++;
      *(p - 3) = *p;
      *p = a;
      p++;
    }
  }
}

Note: You can use the BitConverter.IsLittleEndian to check if the computer is using little endian or big endian internally, so that you can make the code portable.


IIRC, Jon Skeet's MiscUtil library has some code for handling endian-ness.


my universal solution from little endian to int is this:

public static int GetLittleEndianIntegerFromByteArray(byte[] data)
{
    int length = data.Length;
    int result = 0;

    for (int i = length - 1; i >= 0; i--)
    {
        result |= data[i] << i * 8;
    }
    return result;
}


I refactored the function in much simpler syntax:

        private int GetFromBigIndian(byte[] array)
    {
        int value = 0;

        for (int i = 0; i < array.Length; i++)
        {
            value |= (array[i] << i * 8);
        }

        return value;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消