BitArray alternative for the .NET Micro Framework
Asked Answered
C

3

3

Is there a BitArray alternative for the .NET Micro Framework? I was thinking about simply using a bool[], but how can you convert it back into a byte[] ?

In the full framework, considering "bits" is a BitArray, the following works:

byte[] data = new byte[dimensions / 8];
bits.CopyTo(data, 0);

But I cannot seem to find the BitArray class in the micro framework

Conchiferous answered 5/11, 2010 at 14:53 Comment(3)
What exactly do you need? Maybe a byte which you can manipulate is enough?Grosberg
BitArray is implemented using integers and bitwise operatorsHump
@Grosberg nope really needed to operate at the bit level :-)Conchiferous
E
5

It's not terribly difficult to duplicate the functionality of BitArray. First, if you need fewer than 65 bits, then you can do it with a long or smaller.

To set an individual bit:

void Set(ref long ba, int bit)
{
    ba |= 1L << bit;
}

To clear a bit:

void Clear(ref long ba, int bit)
{
    long mask = 1L << bit;
    mask = ~mask;
    ba &= mask;
}

To see if a bit is set:

bool IsSet(long ba, int bit)
{
    long mask = 1L << bit;
    return (ba & mask) != 0;
}

If you have more than 64 bits, then you'll need to create an array (byte[], probably), and do the division to determine which byte/bit you want to modify. The methods above will work, provided you change the long to byte.

For example, if you have:

byte[] myBytes = new byte[128];

You have 1024 bits.

To set a bit:

void Set (int bit)
{
    int byte = bit/8;
    int bitIndex = bit%8;
    myBytes[byte] |= (byte)(1 << bitIndex);
}

The other methods use the same math to get the byte and bit index, and setting, clearing, and testing a bit is the same as with the long example above.

Enclose answered 5/11, 2010 at 15:20 Comment(1)
If Interlocked.CompareExchange is available on the micro framework, one could use that to make any desired types of bit operations atomic. Within a loop, read the old value of the word, compute a new value, and CompareExchange the old value to the new one; reloop until the CompareExchange succeeds. I personally like having an atomic method to compute Thebits = (TheBits & ~Mask) ^ NewBits). Bits which are clear in Mask and NewBits are left alone; those that are clear in Mask and set in NewBits are toggled. Bits that are set in Mask will be copied from NewBits.Dunton
U
2

You can find a BitArray Implementation in the 802.15.4 Stack. Just search the Porting Kit for BitArray.cs

Utoaztecan answered 16/12, 2011 at 8:3 Comment(0)
Y
0

I uploaded an array for .net microframework:

http://code.tinyclr.com/project/310/bitarray-class/

Hope this helps.

Yablon answered 23/5, 2011 at 10:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.