Как я могу реализовать методы getBit и setBit? - PullRequest
0 голосов
/ 22 июня 2019

Я пытаюсь создать свой собственный класс 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; } }
}

Как получить рабочую версию методов getBit и setBit класса, который я создал?Я хочу, чтобы код работал быстро.

1 Ответ

0 голосов
/ 22 июня 2019

Использование битовой маскировки:

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