1

使用 .NET 4.0
使用 dotPeek .NET 反编译器

与 System.BitConverter.ToInt32() 的代码有点混淆:

public static unsafe int ToInt32(byte[] value, int startIndex)
    {
      if (value == null)
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
      if ((long) (uint) startIndex >= (long) value.Length)
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
      if (startIndex > value.Length - 4)
        ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
      fixed (byte* numPtr = &value[startIndex])
      {
        if (startIndex % 4 == 0)
          return *(int*) numPtr;
        if (BitConverter.IsLittleEndian)
          return (int) *numPtr | (int) numPtr[1] << 8 | (int) numPtr[2] << 16 | (int) numPtr[3] << 24;
        else
          return (int) *numPtr << 24 | (int) numPtr[1] << 16 | (int) numPtr[2] << 8 | (int) numPtr[3];
      }
    }

如何理解这部分代码?:

if (startIndex % 4 == 0)
  return *(int*) numPtr;

我的意思是为什么字节数组中的起始位置很重要?

4

1 回答 1

3

numPtr 指向字节数组中存储 32 位值的位置。

如果该地址是 4 字节对齐的,则可以简单地通过强制转换为整数直接读取它:字节指针转换为整数指针,然后将其推迟。

否则,必须单独读取每个字节,然后将它们加在一起以形成 32 位整数。这是因为大多数 CPU 只能在 4 字节对齐的情况下直接读取 4 字节值。

于 2013-01-06T05:31:38.800 回答