1
使用.NET 4.0
使用dotPeek .NET反編譯BitConverter ToInt32 .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;
我的意思是爲什麼字節數組中的起始位置很重要?
你可以給任何關於字節對齊的鏈接嗎? –
http://en.wikipedia.org/wiki/Data_structure_alignment – moopawake
這個關於內存掃描的codeproject文章也非常翔實。 http://www.codeproject.com/Articles/15680/How-to-write-a-Memory-Scanner-using-C – Inisheer