C# Bit Manipulation
This post is a collection of C# method extensions that I have written recently to help me do bit manipulations on unsigned integers. These methods allow you to set, clear, toggle, and write bits. I’ve also added a read method for testing bits.
public static UInt32 SetBit(this UInt32 Value, byte bit) { if (bit >= 32) { throw new ArgumentException("bit must be between 0 and 31"); } Value |= (UInt32)(1U << bit); return Value; } public static UInt32 ClearBit(this UInt32 Value, byte bit) { if (bit >= 32) { throw new ArgumentException("bit must be between 0 and 31"); } Value &= ~(UInt32)(1U << bit); return Value; } public static UInt32 WriteBit(this UInt32 Value, byte bit, bool state) { if (bit >= 32) { throw new ArgumentException("bit must be between 0 and 31"); } if (state) { Value |= (UInt32)(1U << bit); } else { Value &= ~(UInt32)(1U << bit); } return Value; } public static UInt32 ToggleBit(this UInt32 Value, byte bit) { if (bit >= 32) { throw new ArgumentException("bit must be between 0 and 31"); } if ((Value & (1 << bit)) == (1 << bit)) { Value &= ~(UInt32)(1U << bit); } else { Value |= (UInt32)(1U << bit); } return Value; } public static bool ReadBit(this UInt32 Value, byte bit) { if (bit >= 32) { throw new ArgumentException("bit must be between 0 and 31"); } return ((Value & (1 << bit)) == (1 << bit)); }
I also added wrappers so these methods are avaliable UInt16 and Byte types.
c# programming