【发布时间】:2012-07-26 22:41:42
【问题描述】:
我已经很努力了,但我似乎无法理解这段代码中发生了什么。任何人都可以解释一下吗?
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,第三个是ANDing 和NOT,我认为这三行中发生的事情是正确的吗?
1 << (bitPos % 8)1 << (bitPos % 8) 到底在做什么? ANDing、ORing 或 ANDing 和其中的 NOT 会做什么?我所知道的是,您可以左右拉屎某物的价值(或其他,我对此不是很清楚。)那么这是做什么的呢?是 shift 1 还是什么?
谁能解释一下?
编辑:已编辑完整代码...
【问题讨论】:
-
看起来像一个索引属性来返回一个字节的位,为每个位位置返回真/假(分别设置/取消设置),我将发布一个带有详细信息的答案:)
-
看到这个帖子:link
标签: c# arrays boolean bit-manipulation bit-shift