问题
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
回答1:
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.
回答2:
You can find a BitArray Implementation in the 802.15.4 Stack. Just search the Porting Kit for BitArray.cs
回答3:
I uploaded an array for .net microframework:
http://code.tinyclr.com/project/310/bitarray-class/
Hope this helps.
来源:https://stackoverflow.com/questions/4107039/bitarray-alternative-for-the-net-micro-framework