1

我已经很努力了,但我似乎无法理解这段代码中发生了什么。任何人都可以阐明一下吗?

public class BitArrary
{
    private Byte[] m_byteArray;
    private Int32 m_numBits;


    public BitArrary(Int32 numBits)
    {
        if (numBits <= 0)
            throw new ArgumentOutOfRangeException("Must be greater then 0");

        m_numBits = numBits;
        m_byteArray = new Byte[(numBits + 7) / 8];
    }

    public Boolean this[Int32 bitPos]
    {
        get
        {
            if ((bitPos < 0) || (bitPos >= m_numBits))
            {
                throw new ArgumentOutOfRangeException("bitPos");
            }
            else
            {
                return (m_byteArray[bitPos / 8] & (1 << (bitPos % 8))) != 0;
            }
        }
        set
        {
            if ((bitPos < 0) || (bitPos > m_numBits))
                throw new ArgumentOutOfRangeException("bitPos");
            if (value)
            {
                m_byteArray[bitPos / 8] = (Byte)(m_byteArray[bitPos / 8] | (1 << (bitPos % 8)));
            }
            else
            {
                m_byteArray[bitPos / 8] = (Byte)(m_byteArray[bitPos / 8] & ~(1 << (bitPos % 8)));
            }
        }
    }

}

我没有得到对位进行操作的部分(三行)。据我所知,在第一个中,它ANDing是位数组的值,以查找该位是否打开。在第二个中,它ORing,在第三个ANDingNOT,我认为这三行中发生的事情是正确的吗?

这是在做什么,真正伤害我的大脑的是什么1 << (bitPos % 8)?以及它ANDing的作用是什么ORing?我所知道的是,您可以左右拉屎某物的价值(或其他,我对此不是很清楚。)那么这是做什么的呢?是转移还是什么?ANDingNOT1

谁能解释一下?

编辑:编辑完整代码...

4

2 回答 2

2

好的看起来是一个包含字节(m_byteArray)的私有字段,它从字节数组中获取一点(我假设字节数组是连续的,这试图从某个位置获取位 - 例如假设有 3字节,位置 13 将从字节 2 获得位 5)

编辑:更好地总结

图像我们在字节数组中有 3 个字节

00101011 00101010 01000010

如果我们想要第 13 位,我们会将“12”传递给索引器重要的是要记住!!

00101011 00101010 01000010
-------------^
(Remember it's 0 based)

我们去

m_byteArray[12 / 8] (12 / 8 = 1 so we know we want byte number two at index 1 - byte array is also zero based!)

所以我们有第二个字节(在索引 1 处)

00101010
----^

现在我们去

00101010 & (1 << (12 % 8))

这相当于

00101010 & 00000001 << 4

哪个是

00101010 & 00001000

所以这掩盖了

1 & 1

返回 1 :)

对于最终成为

1 & 0

逻辑上返回 0

于 2012-07-28T14:02:41.303 回答
1

该行:

return (m_byteArray[bitPos / 8] & (1 << (bitPos % 8))) != 0;

返回是否设置了字节数组中的第 n 位。

bitPos / 8

找到索引位所在的字节,并且

1 << (bitPos % 8))

为相关字节创建一个位掩码。

例如,如果要查找第 10 位是否已设置,则为bitPos9. bitPos / 8= 1,因此相关位位于数组中的第二个字节中。 bitPos % 8= 1,因此表达式 (1 << (bitPos % 8)) 创建了00000010. 如果设置了第二个位,则应用此掩码byteArray[1]将返回 1,否则返回 0。

设置器的逻辑是相似的,除了

m_byteArray[bitPos / 8] | (1 << (bitPos % 8))

将在相关位置设置位,而

(m_byteArray[bitPos / 8] & ~(1 << (bitPos % 8))

将清除它。

于 2012-07-28T14:03:10.627 回答