获得更高的使用位位置

Get higher used bit position

我有一些 int32 值。 我需要获得更高位的位置,用于表示当前值。

例如:

int value = 155;

二进制形式为10011011 所以使用的更高位有位置 8.

是否有任何默认或通用方法?

pos 将是基于 0 的索引

var pos = (int)Math.Log(155, 2);

当然你应该检查yourval>0

有关更棘手的问题,请参阅 https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogIEEE64Float

GetBit 每一位都可以检查 true(1) 或 false(0) 和 32 位循环查找第一个 true 位的索引。

public static class ByteExtensions
{
    public static bool GetBit(this byte byteValue, int bitIndex)
    {
        return (byteValue & (1 << bitIndex - 1)) != 0;
    }
    public static int GetMaxBitIndex(this byte byteValue)
    {
        for (int i = 32; i > -1; i--)
        {
            if (byteValue.GetBit(i))
                return i;
        }
        return -1;
    }
}