bit Fields in c# structs ??

  • Thread starter Thread starter Sagaert Johan
  • Start date Start date
No, and i'd advise against using them even if they were there, but you can
create a structure\class that works like one internally with a little work.
This would be of use only if you need to produce in memory values perhaps to
send to legacy platform code or writing to files that expect bit fields. In
any other condition, just use a normal class and don't worry about space.

Basically, you would encapsulate a BitVector32 or BitArray and provide
boolean & int properties that set bits. You will have to worry about any
possible endian issues, etc, but that shouldn't be much of a problem. This
should allow you to create structures that have the memory equivilent of a
bit vector (marshalling should deal with just the internal BitVector & not
the various properties), or classes that expose a BitVector32 that can be
written to a file containing the proper data format.

Some caevets however, are that bitvector based structures that require ints
will either require you to figure out what bits need be set yourself, or
possibly a custom marshaller that will ignore the Section objects and any
other data you might need to keep track of location.
You will also have to explicitly lay out the BitVector32 fields location if
more than one exists.
I am assuming BitVector32 marshals properly however, it might not, and i
don't really have anything to test with, ;).
 
Sagaert,
You can define a new Enum with the FlagsAttribute to come close to
'bitfields'.

Or as Daniel stated, a BitArray or BitVector32 might do it.

Otherwise as Mattias stated: bitfields in the C++ sense of the word are not
supported.

Hope this helps
Jay
 
I came to the conclusion to use a struct in my C# and then convert it to
what my embedded system would expect in memory.



Chad Myers said:
Sagaert Johan said:
does c# provide bitfields in structs ??

can't find any hint in msdn

Use the [Flags] attribute on an an enumerator.

[Flags]
public enum PizzaToppings
{
ExtraCheese = 1,
Pepperoni = 2,
ItalianSausage = 4,
AmericanSausage = 8,
Peppers = 16,
Mushrooms = 32,
Anchovis = 64,
Pineapples = 128
}

...

public class Pizza
{
private PizzaToppings toppings;

public PizzaToppings Toppings
{
get{ return toppings; }
set{ toppings = value; }
}

... blah blah
}

...

Pizza p = new Pizza();

p.Toppings =
PizzaToppings.ExtraCheese |
PizzaToppings.ItalianSausage |
PizzaToppings.Pepperoni;


-c
 
Back
Top