2013-01-06 39 views
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; 

我的意思是爲什麼字節數組中的起始位置很重要?

回答

3

numPtr指向存儲32位值的字節數組中的位置。

如果這個地址是4字節對齊的,它可以直接通過強制轉換爲整數來讀取:字節指針被轉換爲整數指針,然後這被推定。

否則,必須單獨讀取每個字節,然後將它們加起來構成一個32位整數。這是因爲如果4字節對齊,大多數CPU只能直接讀取4字節值。

+1

你可以給任何關於字節對齊的鏈接嗎? –

+0

http://en.wikipedia.org/wiki/Data_structure_alignment – moopawake

+2

這個關於內存掃描的codeproject文章也非常翔實。 http://www.codeproject.com/Articles/15680/How-to-write-a-Memory-Scanner-using-C – Inisheer

相關問題