I have the following code for getting the MSB (Most Significant Bit) from a non-negative integer, Int32
to be more specific:
private static readonly int[] powersOf2 = new int[]
{
1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304,
8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912,
1073741824
};
public static int GetMsb(int value)
{
for (int k = powersOf2.Length - 1; k >= 0; k--)
{
var bit = (value & powersOf2[k]) != 0;
if (bit)
return (k + 1);
}
return 0;
}
Again: given that value is not negative.
My question is:
Does the .NET framework guarantee that this code would run appropriately on every platform: x86/Windows/Linux/Sun/64bit?
Is the Int32
representation inside .NET, including Endianness and bit/byte order, platform agnostic?
Thanks in advance!
BTW, if this is kind of a duplicate - please comment about it ASAP. Thanks!
As long as you treat it as an
int
, yes it is platform agnostic. This includes all arithmetic and bitwise (<<
,>>
etc) operations. The opcodes always make sure that it does what you expect.However! If you peek below the covers, it might matter; for example
BitConverter.GetBytes(int)
andBitConverter.ToInt32
care about the endianness. You can check this withBitConverter.IsLittleEndian
; it is usuallytrue
on "regular" .NET, but could befalse
perhaps on IA64, or XNA or Mono on some architectures.The same logic applies to any unsafe code that coerces (for example) between
byte*
andint*
, or any unions constructed via[StructLayout]
.But in regular code, you should be fine.