简体   繁体   English

如何实现 getBit 和 setBit 方法?

[英]How can I implement the getBit and setBit methods?

I'm trying to create my own BitArray class.我正在尝试创建自己的 BitArray 类。 How do I change the desired bit of a byte?如何更改字节的所需位?

public class MyBitArray
{
    byte[] bytes;

    public MyBitArray(long limit, bool defaultValue = false)
    {
        long byteCount = (limit >> 3) + 1;
        bytes = new byte[byteCount];
        for(long i = 0; i < byteCount; i++)
        {
           bytes[i] = (defaultValue == true ? (byte)0xFF : (byte)0x00);
        }
        this.limit = limit;
    }

    public bool this[long index]
    {
        get
        {
            return getValue(index);
        }
        set
        {
            setValue(index, value);
        }
    }

    bool getValue(long index)
    {
        long byteIndex = (index & 7) == 0 ? ((index >> 3) - 1) : index >> 3;
        byte bitIndex = (byte)(index % 8);

        return getBit(bytes[byteIndex], bitIndex);
    }

    void setValue(long index, bool value)
    {
       long byteIndex = (index & 7) == 0 ? (index >> 3) - 1 : index >> 3;
       byte bitIndex = (byte)(index % 8);

       bytes[byteIndex] = setBit(bytes[byteIndex], bitIndex, value);
    }

    bool getBit(byte byt, byte index)
    {
        if (index < 0 || index > 7)
            throw new ArgumentOutOfRangeException();

        return ?? // change bit and then return bool value if 0 false else true
    }



    byte setBit(byte byt, byte index, bool value)
    {
        if (index < 0 || index > 7)
            throw new ArgumentOutOfRangeException();

        return ?? // change bit and then return changed byte
    }

    private long limit;
    public long Limit { get { return limit; } }
}

How can I get a working version of the getBit and setBit methods of the class I created?如何获得我创建的类的getBitsetBit方法的工作版本? I want the code to run fast.我希望代码运行得快。

Using bit masking:使用位掩码:

    bool getBit(byte byt, byte index)
    {
        if (index < 0 || index > 7)
            throw new ArgumentOutOfRangeException();

        return (byt & (1 << index)) >> index;
    }



    byte setBit(byte byt, byte index, bool value)
    {
        if (index < 0 || index > 7)
            throw new ArgumentOutOfRangeException();

        return (byt & ~(1 << index)) + (value ? 1 << index : 0);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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