I've tried really hard, but I can't seem to understand what's going on in this code. Can anyone please shed some light?
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)));
}
}
}
}
I don't get the parts (the three lines) where there is operation on bits. As far as I get it, in first one, its ANDing
the value of bit array to find if that bit is on. In second one, its ORing
, and in the third one ANDing
with NOT
, is that about right what I think is happening in these three lines?
Whats really hurting my brain in what is this doing 1 << (bitPos % 8)
? And what does ANDing
, ORing
or ANDing
with NOT
of it, is going to do? What I know is that you can left or right shit a value of something (or other, I am not really clear on this.) So what is this doing? is it shift 1
or what?
Can anyone please explain?
EDIT : Edited for full code...