views:

155

answers:

2

I have an application that requires manipulating nybbles and possibly even individual bits at a time. Is there a library in C# that can help me?

+5  A: 

You can use BitVector32 to manipulate bits in a 32 bit integer and BitArray to have an array of bits representing a set of boolean variables.

Also, it's pretty easy to write a couple functions to manipulate individual bits:

public bool GetBitValue(int integer, int bit) {
    return (integer & (1 << bit)) != 0; 
}

public bool SetBitValue(ref int integer, int bit, bool value) {
    if (value)
        integer |= 1 << bit;
    else
        integer &= ~(1 << bit);
}
Mehrdad Afshari
Elegant solution, I like it!
ParmesanCodice
+1  A: 

A library is really unnecessary

uint myVar = 257;
const uint SOME_FLAG_A = 256 // 100000000
const uint SOME_FLAG_B = 16  // 000010000
const uint SOME_FLAG_C = 1   // 000000001

if(myVar & SOME_FLAG_A == SOME_FLAG_A)
   Console.WriteLine("Bit A is set!");
else
   Console.WriteLine("Bit A is not set.");

if(myVar & SOME_FLAG_B == SOME_FLAG_B)
   Console.WriteLine("Bit B is set!");
else
   Console.WriteLine("Bit B is not set.");

myVar = myVar | SOME_FLAG_B;

if(myVar & SOME_FLAG_B == SOME_FLAG_B)
   Console.WriteLine("Bit B is set!");
else
   Console.WriteLine("Bit B is not set.");

if(myVar & SOME_FLAG_C == SOME_FLAG_C)
   Console.WriteLine("Bit C is set!");
else
   Console.WriteLine("Bit C is not set.");
Spencer Ruport