英文:
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;
}
& ~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 <= m_MaxCapacity);
int newCapacity = Capacity;
// Round the current capacity to the nearest multiple of 2
// that is larger than the required capacity.
if (newCapacity < requiredCapacity)
{
newCapacity = (requiredCapacity + 1) & ~1;
}
return newCapacity;
}
What does exactly mean by & ~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. &
, the bitwise-and operator, means to keep only the bits set in both operands (this operation is often referred to as "masking"). So & ~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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论