No Unnecessary Bit Operation

ID

csharp.no_unnecessary_bit_operation

Severity

critical

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

redundancy, reliability, suspicious-operator

Description

Reports a bitwise expression whose operand is the identity value for the operator applied, so the operation cannot change the result. x & -1, x | 0 and x ^ 0 all evaluate to x, and the compound assignments x &= -1, x |= 0 and x ^= 0 all leave x as it was.

Rationale

Integral values are stored in two’s complement, so -1 has every bit set: masking a value with it keeps every bit and returns the value untouched. The literal 0 has no bit set, so neither | nor ^ can flip anything. Either the expression is dead weight the reader still has to decode, or the constant is simply wrong — a mask that was meant to be narrowed, or a flag constant that was renamed away and left a zero behind.

The mirror-image constants are not reported, because they are not identities and are frequently deliberate: x & 0 always evaluates to 0, and x | -1 always evaluates to -1.

public class Flags
{
    public int Keep(int value)
    {
        return value & -1;        // FLAW — every bit survives the mask
    }

    public int Set(int value)
    {
        return value | 0;         // FLAW — no bit is set
    }

    public int Flip(int value)
    {
        return value ^ 0;         // FLAW — no bit is flipped
    }

    public int Narrow(int value)
    {
        value &= -1;              // FLAW — the compound form of the same no-op
        return value;
    }

    public int Clear(int value)
    {
        return value & 0;         // OK — collapses to zero, which is a real effect
    }

    public int LowBit(int value)
    {
        return value & 1;         // OK — keeps the low bit only
    }
}

Remediation

Drop the operation and use the operand directly. If the constant was supposed to be a real mask, correct it to the intended value — check whether a named constant was renamed or removed and left the literal behind.