Convert bitfield to array

I have a uint called Forced containing 32 bits.

I am doing things like:

if(Forced & 512)
   doStuff();

What I want to do is put into an array, which then turns into:

if(ForcedArray[(int)Math.Log(512,2)])
   doStuff();

Is there a convenient way in .NET to do this? What would be a convenient way to convert a bit field to an array?

+4
source share
3 answers

You can write an extension method for this:

public static class UIntExtensions
{
    public static bool IsBitSet(this uint i, int bitNumber)
    {
        return i & (1 << bitNumber) != 0;
    }
}

Or, if you want to do this, C # 6:

public static class UIntExtensions
{
    public static bool IsBitSet(this uint i, int bitNumber) => (i & (1 << bitNumber)) != 0;
}

Which is pretty easy to use from code:

if(Forced.IsBitSet((int)Math.Log(512,2)))
   doStuff();

Obviously, you need to add a few checks for the presence of the bit number> = 0 or <= 31, but you get this idea.

+3
source

- Forced & (1 << bitNumber) ( ).

, . , , ( API, JSON) .

, ( ).

, - for LINQ . (, , , , ):

var array = Enumerable.Range(0, 32)
  .Select(bitNumber => (Forced & (1 << bitNumber)) !=0)
  .ToArray();
+3
public static class UIntExtensions
{
    public static byte[] GetBitArray(this uint v)
    {
        var r = byte[32];
        for (var i = 0; i < 32; ++i)
        {
            r[i] = v & 1;
            v = v >> 1
        }
        return r;
    }
}
0
source

Source: https://habr.com/ru/post/1619978/


All Articles