BitArray alternative for the .NET Micro Framework

泪湿孤枕 提交于 2019-12-01 07:02:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!