BitFlags

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

is there any inbuit feature in c# for bitflags

im looking for somethin that could take in the constructor a numerial value eg 5 then internaly would conver that so u could access it as bool 1, 0, 1. so they could be easily tested in if's et

does anything like this exist? or is there an easy way to create it?
 
how about

using System;
using System.Diagnostics;


namespace BitFields
{
class BitFields
{
public BitFields(long val)
{
Value = val;
}

public long Value;
public bool this[int index]
{
get { return (Value & 1<<index) != 0; }
set
{
Value = Value & ~(1<<index);
if(value)
Value |= 1<<index;
}
}
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
BitFields bf = new BitFields(5);
Trace.Assert(bf[0]);
Trace.Assert(!bf[1]);
Trace.Assert(bf[2]);
bf[1] = true;
Trace.Assert(bf.Value == 7);
}
}
}
 
Uri Dor said:
how about

using System;
using System.Diagnostics;


namespace BitFields
{
class BitFields
{
public BitFields(long val)
{
Value = val;
}

public long Value;
public bool this[int index]
{
get { return (Value & 1<<index) != 0; }
set
{
Value = Value & ~(1<<index);
if(value)
Value |= 1<<index;
}
}
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
BitFields bf = new BitFields(5);
Trace.Assert(bf[0]);
Trace.Assert(!bf[1]);
Trace.Assert(bf[2]);
bf[1] = true;
Trace.Assert(bf.Value == 7);
}
}
}

is there any inbuit feature in c# for bitflags?

im looking for somethin that could take in the constructor a numerial
value eg 5 then internaly would conver that so u could access it as bool
1, 0, 1. so they could be easily tested in if's etc

does anything like this exist? or is there an easy way to create it?

You may also want to consider System.Collections.BitArray and
System.Collections.Specialized.BitVector32(be careful, it has a bug that
keeps the high bit set at all times, IIRC)
 
Thanks, Daniel, I forgot about BitArray
how about

using System;
using System.Diagnostics;


namespace BitFields
{
class BitFields
{
public BitFields(long val)
{
Value = val;
}

public long Value;
public bool this[int index]
{
get { return (Value & 1<<index) != 0; }
set
{
Value = Value & ~(1<<index);
if(value)
Value |= 1<<index;
}
}
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
BitFields bf = new BitFields(5);
Trace.Assert(bf[0]);
Trace.Assert(!bf[1]);
Trace.Assert(bf[2]);
bf[1] = true;
Trace.Assert(bf.Value == 7);
}
}
}


Spike wrote:

is there any inbuit feature in c# for bitflags?

im looking for somethin that could take in the constructor a numerial
value eg 5 then internaly would conver that so u could access it as bool
1, 0, 1. so they could be easily tested in if's etc

does anything like this exist? or is there an easy way to create it?


You may also want to consider System.Collections.BitArray and
System.Collections.Specialized.BitVector32(be careful, it has a bug that
keeps the high bit set at all times, IIRC)
 
Back
Top