BitArray

作者:追风剑情 发布于:2017-3-24 14:47 分类:C#

using System;
/// <summary>
/// Bit索引器类
/// </summary>
public sealed class BitArray {

    private byte[] m_byteArray;
    private Int32 m_numBits;

    public BitArray(Int32 numBits)
    {
        if (numBits <= 0)
            throw new ArgumentOutOfRangeException("numBits must be > 0");

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

    public Int32 Length
    {
        get
        {
            return m_numBits;
        }
    }

    //索引器
    //编译器会默认生成get_Item和set_Item访问器
    //也可以用System.Runtime.CompilerServices.IndexerNameAttribute来重命名访问器
    //[IndexerName("Bit")]
    public Boolean this[Int32 bitPos]
    {
        get
        {
            if (bitPos < 0 || bitPos >= m_numBits)
                throw new ArgumentOutOfRangeException("bitPos");

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

        set
        {
            if (bitPos < 0 || bitPos >= m_numBits)
                throw new ArgumentOutOfRangeException("bitPos", bitPos.ToString());

            if (value)
            {
                //将指定索引处的位设为true
                m_byteArray[bitPos / 8] = (Byte)(m_byteArray[bitPos / 8] | (1 << (bitPos % 8)));
            }
            else
            {
                //将指定索引处的位设为false
                m_byteArray[bitPos / 8] = (Byte)(m_byteArray[bitPos / 8] & ~(1 << (bitPos % 8)));
            }
        }
    }
}


System.Collections.BitArray

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号