diff --git a/Core/Extensions/BitHelper.cs b/Core/Extensions/BitHelper.cs new file mode 100644 index 00000000..c8d54148 --- /dev/null +++ b/Core/Extensions/BitHelper.cs @@ -0,0 +1,27 @@ +using System; + +namespace Vanara.Extensions +{ + /// Static methods to help with bit manipulation. + public static class BitHelper + { + /// Gets the bit value at the specified index in a bit vector. + /// The type of the bit vector. Must be of type . + /// The bit vector. + /// The index of the bit to get. + /// if the bit is set (1); otherwise. + public static bool GetBit(ref T bits, byte idx) where T : IConvertible => (bits.ToInt64(null) & 1 << idx) != 0; + + /// Sets the bit value at the specified index in a bit vector. + /// The type of the bit vector. Must be of type . + /// The bit vector. + /// The index of the bit to set. + /// If set to , set the bit (= 1); otherwise, clear the bit (= 0). + public static void SetBit(ref T bits, byte idx, bool value) where T : IConvertible + { + long bit = 1 << idx; + var l = bits.ToInt64(null); + bits = (T)(object)(value ? l | bit : l & ~bit); + } + } +} \ No newline at end of file