Shifting a BitArray

后端 未结 2 794
天涯浪人
天涯浪人 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.

    0 讨论(0)
  • 2021-01-27 06:36
    public static bool[] Left_shiftBitArray(bool[] Array, int count)
            {
                Array = BitArray_LRotat(Array, count);
                for (int i=Array.GetLength(0)-1; i>=(Array.GetLength(0)-count); i--)
                {
                    Array[i] = false;
                }
    
                return Array;
            }
    
            public static bool[] BitArray_LRotat(bool[] input, int x)
            {
                //bool [] temp= new bool[input.Length];
                bool[] final = new bool[input.Length];
                for (int i = input.Length; i > x; i--)
                {
                    final[i - x - 1] = input[i - 1];
                }
                for (int i = x; i > 0; i--)
                {
                    final[(input.Length) - i] = input[x - i];
                }
                return final;
            }
    
    0 讨论(0)
提交回复
热议问题