Search code examples
c#bit-manipulationbitwise-operatorsstringbuilder

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


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


Solution

  • ~ 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.