无法理解在Stringbuilder内部方法中位运算符中的`&`和`~`语法。

huangapple go评论116阅读模式
英文:

Can't understand & ~ syntaxes in a bitwise operator in Stringbuilder internal method

问题

关于StringBuilder类的描述:

private int GetReplaceBufferCapacity(int requiredCapacity)
{
    // 此函数假设所需容量将小于StringBuilder的最大容量
    Diagnostics.Debug.Assert(requiredCapacity <= m_MaxCapacity);

    int newCapacity = Capacity;
    // 将当前容量四舍五入为大于所需容量的最近2的倍数。
    if (newCapacity < requiredCapacity)
    {
        newCapacity = (requiredCapacity + 1) & ~1;
    }
    return newCapacity;
}

&amp; ~1 的意思是将 requiredCapacity + 1 的结果与二进制的 ~1 操作进行与运算。在这里,~1 表示将二进制中的所有位取反,即将所有位从0变为1,从1变为0。这个操作的目的是将 requiredCapacity + 1 的最低位(最右边的位)设置为0,以确保它是偶数。这是因为新容量需要是2的倍数,所以通过将最低位设置为0,可以实现四舍五入到最接近的偶数。

英文:

From the description of StringBuilder class:

private int GetReplaceBufferCapacity(int requiredCapacity)
    {
        // This function assumes that required capacity will be less
        // than the max capacity of the StringBuilder
        Diagnostics.Debug.Assert(requiredCapacity &lt;= m_MaxCapacity);

        int newCapacity = Capacity;
        // Round the current capacity to the nearest multiple of 2
        // that is larger than the required capacity.
        if (newCapacity &lt; requiredCapacity)
        {
            newCapacity = (requiredCapacity + 1) &amp; ~1;
        }
        return newCapacity;
    }

What does exactly mean by &amp; ~1?

Update 15 March 2023

For all new users who come across this post - please check this guide on Microsoft site: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators

答案1

得分: 3

~是一元位求反运算符,所以1,它的低位设置而其他位未设置,变成了一个低位未设置而其他位设置的值。&,位与运算符,意味着只保留两个操作数中都设置的位(这个操作通常被称为“掩码”)。所以& ~1取消了另一个操作数的低位,保留了其他位。

由于代码已经添加了1,如果requiredCapacity最初是偶数,那么添加1会设置低位,而掩码会再次移除它。如果requiredCapacity最初是奇数,增量将其提升到下一个偶数,掩码不会产生任何效果。

简而言之,它正是评论所说的:

// 将当前容量舍入到大于所需容量的最接近的2的倍数。

英文:

~ is the unary bitwise-invert operator, so 1, which has the low bit set and all other bits unset, becomes a value with the low bit unset, and all other bits set. &amp;, the bitwise-and operator, means to keep only the bits set in both operands (this operation is often referred to as "masking"). So &amp; ~1 unsets the low bit of the other operand, keeping the rest.

Since the code already added 1, if requiredCapacity was originally even, then adding 1 sets the low bit, and the masking removes it again. If requiredCapacity was originally odd, the increment moves it up to the next even number, and the masking does nothing.

In short, it does exactly what the comment says:

    // Round the current capacity to the nearest multiple of 2
    // that is larger than the required capacity.

huangapple
  • 本文由 发表于 2023年3月7日 06:35:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定