Shifting a BitArray

后端 未结 2 799
天涯浪人
天涯浪人 2021-01-27 06:23

I\'m currently trying to shift a BitArray while keeping its length. Since there\'s no built-in method I\'m struggling to build one but can\'t make it work, unfortunatly.

2条回答
  •  臣服心动
    2021-01-27 06:36

    Still not 100% sure what's the issue. Here's a naive implementation:

    void Main()
    {
        // Creates and initializes a BitArrays of size 7 (you have 421).
        bool[] myBools = new bool[7] { true,false,false,true,true,false,true };
        BitArray myBA1 = new BitArray(myBools );
    
        PrintBitArray(myBA1);              // 1001101
        PrintBitArray(ShiftRight(myBA1));  // 0100110
        PrintBitArray(ShiftLeft (myBA1));  // 0011010
    }
    
    BitArray ShiftRight(BitArray aSource) {
        bool[] new_arr  = new bool[( aSource.Count)];
        for (int i = 0; i < aSource.Count -1; i++)
            new_arr[i+1] = aSource[i];
    
        return new BitArray(new_arr);
    }   
    
    BitArray ShiftLeft(BitArray aSource) {
        bool[] new_arr  = new bool[( aSource.Count)];
        for (int i = 0; i < aSource.Count -1; i++)
            new_arr[i] = aSource[i+1];
    
        return new BitArray(new_arr);
    }
    
    string PrintBitArray(BitArray aSource) {
        StringBuilder sb  = new StringBuilder();
        foreach (var bit in aSource)
        {
            sb.Append( (bool)bit ? 1 : 0 );
        }
        return sb.ToString();
    }
    

    Note how bits are copied in the loops, and that the third PrintBitArray is done on the original input, not on the outcome of the second.

提交回复
热议问题