October 16, 2023

Bit Operations

An extension class that allows various bitwise operations on an integer to be performed when dealing with a [Flags] Enum type.

// Bit wise operations on an integer as an extensions class
public static class IntBitwiseOperationsExtender
{
    // Returns bits set in lhs or rhs or both
    public static int BitwiseUnion(this int lhs, int rhs)
    {
        int bitWiseOr = lhs | rhs;
        return bitWiseOr;
    }

    // Return bits set common to both lhs and rhs
    public static int BitwiseIntersection(this int lhs, int rhs)
    {
        return lhs & rhs;
    }

    // Returns bits set in lhs or rhs but not in both
    public static int BitwiseExclusiveOr(this int lhs, int rhs)
    {
        int exclusiveOr = BitwiseUnion(lhs, rhs) - BitwiseIntersection(lhs, rhs);
        return exclusiveOr;
    }

    // Return lhs bits inverted, 0s becomes 1s and vice versa
    public static int BitwiseInvert(this int lhs)
    {
        int bitWiseOr = ~lhs;
        return bitWiseOr;
    }

    // Return lhs bits set minus any that are also set in the rhs
    public static int BitwiseRemove(this int lhs, int rhs)
    {
        int common = BitwiseIntersection(lhs, rhs); // Find the bits common to both sides
        int res = (int)lhs - (int)common;
        return res;
    }

    // Return a value that has all the bits set either in the lhs part or in the rhs part or both
    public static int BitwiseOr(this int lhs, int rhs)
    {
        return BitwiseUnion(lhs, rhs); // Same as a Bitwise Union
    }

    // Return true if lhs contains all the bits set within rhs
    public static bool BitwiseContains(this int lhs, int rhs)
    {
        int common = lhs & rhs;
        return (common == rhs);
    }

    // Return true if lhs contains one of the bits set within rhs
    public static bool BitwiseContainsOneOf(this int lhs, int rhs)
    {
        int common = lhs & rhs;
        return common > 0;
    }
}

No comments: