Integer Based Bit Manipulation - C#

As a follow up to my post from yesterday, here is the C# extension version of the integer bit manipulation.  In order to facilitate the code I post, I have created a Codeplex project.  The project name is Pickle, from my last name.  It's going to be a kitchen sink project with all sorts of utilities in it.

As it stands now, I have one solution with five projects in it.  I have a Core project where I'm keeping my extension methods and various utilities, a database project where I'm keeping things like PrintMax and the SQL bit manipulation, a SQLCLR project where I've got my double byte encoding function, since I'm trying to get into TDD I also have a Unit Test project and finally I have a web project where I'm splashing around with various things.  That was a run-on sentence to end all run-on sentences.  Perhaps codeplex is overkill, but it just seemed to make sense.  Instead of posting code, from now on I'll post screenshots and links to the source code on codeplex.

Extension Methods

As promised, I have created C# extension methods for the bit manipulation.  The can be used to test integer values throughout your project.  I have created the same set of functions (IsBit, ReadBit, SetBit, IsBitUnion).

Here is a look at the SetBit extension method:

CSharpBitExtensionCode

And here is a look at the IsBitUnion usage:

CSharpBitExtensionUsage

For these two calls IsBitUnion returned true then false as expected.

Here is a link to the source code file in my codeplex project that contains the bit and other extension methods.

By the way.  I'm not sure what version of TFS Codeplex is running, but I thought I saw that they were using 2005.  I'm running the VS.Net 2008 Team Suite with the TFS 2008 plug-in and connecting with no issues.  This is exciting for me, I wasn't sure if the VS.Net 2k8 worked with TFS 2k5.  Really, I'm still not sure, but I'm feeling better :D

All feedback is encouraged.

Thanks,
Ben

2 Comments

  • Interesting.
    How about this:

    return state ? (target | bit) : (target & ~bit);

    This single line can replace your whole SetBit method :-)

  • YZ: Nope it can't, you missed the bit about ensuring there is only 1 bit set ;-)

    System.Collections.Specialized.BitVector32 would be the pre-cooked solution.

    anyways, in the usage code snippet given i would be much happier if an enum with the flags attribute was used like:

    [Flags]
    public enum Permissions
    {
    None = 0,
    Read = 1,
    Write = 2,
    Delete = 4,
    ReadWrite = Read | Write,
    Admin = ReadWrite | Delete,
    }

    then you could do:

    Permissions p = Permissions.Read | Permissions.Write

    testing would be a but ugly though:

    bool readable = (p & Permissions.Read) == Permissions.Read;

    But that could be fixed a few finely crafted extension methods...

Comments have been disabled for this content.