简体   繁体   中英

How to get single byte out of BitArray (without byte[])?

I was wondering, is there a way to convert a BitArray into a byte (opposed to a byte array)? I'll have 8 bits in the BitArray..

 BitArray b = new BitArray(8);


//in this section of my code i manipulate some of the bits in the byte which my method was given. 

 byte[] bytes = new byte[1];
 b.CopyTo(bytes, 0);

This is what i have so far.... it doesn't matter if i have to change the byte array into a byte or if i can change the BitArray directly into a byte. I would prefer being able to change the BitArray directly into a byte... any ideas?

You can write an extension method

    static Byte GetByte(this BitArray array)
    {
        Byte byt = 0;
        for (int i = 7; i >= 0; i--)
            byt = (byte)((byt << 1) | (array[i] ? 1 : 0));
        return byt;
    }

You can use it like so

        var array = new BitArray(8);
        array[0] = true;
        array[1] = false;
        array[2] = false;
        array[3] = true;

        Console.WriteLine(array.GetByte()); <---- prints 9

9 decimal = 1001 in binary

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