如何实现getBit和setBit方法?

时间:2019-06-22 17:31:25

标签: c# bit

我正在尝试创建自己的BitArray类。如何更改所需的字节位?

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; } }
}

如何获得我创建的类的getBitsetBit方法的有效版本?我希望代码能快速运行。

1 个答案:

答案 0 :(得分:0)

使用位屏蔽:

    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);
    }