使用.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;我的意思是为什么字节数组中的起始位置很重要?
发布于 2013-01-06 13:31:39
numPtr指向字节数组中存储32位值的位置。
如果该地址是4字节对齐的,则可以通过转换为整数直接读取该地址:将字节指针转换为整数指针,然后对其进行延迟。
否则,必须单独读取每个字节,然后将其相加以构成32位整数。这是因为大多数CPU只能在4字节对齐的情况下直接读取4字节值。
https://stackoverflow.com/questions/14179573
复制相似问题