Using .NET 4.0
Using dotPeek .NET decompiler
A little bit confused with code of 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];
}
}
How to understand this part of code?:
if (startIndex % 4 == 0)
return *(int*) numPtr;
I mean why start position in byte array matters?
numPtr points to the location in the byte array where the 32-bit value is stored.
In the event that this address is 4-byte aligned, it can simply be read directly through a cast to an integer: the byte pointer is converted to an integer pointer and then this is deferenced.
Otherwise, each byte must be read individually and then added together to make a 32-bit integer. This is because most CPUs can only read 4-byte values directly if they are 4-byte aligned.