.NET Is MSB for int32 platform agnostic?

I have the following code to get 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: if this value is not negative.

My question is:
Is the .NET Framework a guarantee that this code will work on every platform: x86 / Windows / Linux / Sun / 64bit?

Is the view Int32inside .NET, including Endianness and bit / byte order, platform agnostic?

Thanks in advance! By the way, if this is a kind of duplicate, comment on it as soon as possible. Thank!

+3
source share
4 answers

int, , . (<<, >> ..). , , .

! , ; , BitConverter.GetBytes(int) BitConverter.ToInt32 . BitConverter.IsLittleEndian; true "".NET, false, , IA64 XNA Mono .

, () byte* int* , [StructLayout].

.

+3

, .

Endianness , , , (StructLayout: Explicit) BitConverter.

, endian.

+2

.

, Int32 , , , : ANDing Int32s Int32. , , , 2, .

+1

The code is portable, however, it returns 0 as the MSB for int.MinValue, which is actually 0x80000000 in hexa, because you are working with integer characters. Here is a code that works for all bits, I believe, and does not need any pre-calculated values:

public static int GetMsb(int value)
{
    for(int i = 31; i >= 0; i--)
    {
        if ((value & 0x80000000) != 0) return i;
        value <<= 1;
    }
    return 0;
}

or with uint:

public static int GetMsb(uint value)
{
    for(int i = 31; i >= 0; i--)
    {
        if ((value & 0x80000000) != 0) return i;
        value <<= 1;
    }
    return 0;
}
0
source

Source: https://habr.com/ru/post/1781958/


All Articles