简体   繁体   中英

Convert 16-bit unsigned integer status word to bitarray

I have searched high and low to find an easy way (like in C++) to do this in C#, I guess I don't know the specific search terms. In C++ I use the code below to put in a 16 bit unsigned integer, then I can use it to easily get to the individual bits. How do I do this in C#? I tried BitArray , but it doesn't seem to provide a way to put in an unsigned 16 bit value and then get to the bits. Perhaps BitArray isn't the way.

Using this way I can read the status register value from my device (a stepper motor) assign this value to the bitfield and easily access bits inside it without extra code.

Help is very appreciated.

typedef union bitfield16_union
{
    U16 uiWord;    // unsigned short
    struct
    {
        unsigned short    b0 : 1;      // LSB
        unsigned short    b1 : 1;
        unsigned short    b2 : 1;
        unsigned short    b3 : 1;
        unsigned short    b4 : 1;
        unsigned short    b5 : 1;
        unsigned short    b6 : 1;
        unsigned short    b7 : 1;
        unsigned short    b8 : 1;
        unsigned short    b9 : 1;
        unsigned short    b10 : 1;
        unsigned short    b11 : 1;
        unsigned short    b12 : 1;
        unsigned short    b13 : 1;
        unsigned short    b14 : 1;
        unsigned short    b15 : 1;      // MSB
    } b;
    // ************
} BITFIELD16;
// ************


main
{ 
BITFIELD16 statusWord;

statusWord.uiWord = 154;
if(statusWord.b.b3) {do something}
} 

While C# does support overlapped structs with explicit layout, it doesn't support it down to the level of individual bits. As such, your best bet here is probably to use bit operations instead. This isn't necessarily arduous:

public ushort Value { get; set; }
public bool this[int index] {
    get => (Value & (1 << index)) != 0;
    set {
        if (value) Value |= (ushort)(1 << index);
        else Value &= (ushort)~(1 << index);
    }
} // Note untested

usage:

bool b3 = thing[3];
thing[5] = false;

You can convert a uint32 to its binary string representation using Convert.ToString() .

uint32 someNumber = 16384;
string binaryString = Convert.ToString(someNumber, 2);

From there you can create an array of Booleans using Select .

bool[] bits = binaryString.Select( x => x == '1' ).ToArray();

Depending on how you wish to index into the bit array, you may want to reverse it. Reversing it means the least significant bit will be at index 0:

bool[] bits = binaryString.Reverse().Select( x => x == '1' ).ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM