我目前正在嘗試在保持其長度的同時移位BitArray。由於沒有內置的方法,我正在努力構建一個,但不能使它工作,不幸的是。移位BitArray
我的初始BitArray代碼設置BitArray的長度爲421。
var b = new BitArray(length: 421);
比,我正在分配一些值進行測試。例如: b.Set(0,true); b。Set(1,true);我不知道如何移動位數組。 嘗試次數: - 我認爲我可以將它轉換爲長時間,並進行位操作。但是,long與我的確切BitArray長度不匹配,這會導致稍後在對兩個BitArrays應用按位操作時發生錯誤(我的全部要求是(array1 | = array2 >> 20)。 - 我試圖將BitArray轉換爲字節[],執行操作,並返回它(見Bit shifting N bits):
public static byte[] ToBytesArray(this BitArray array, int startIndex, int count)
{
// Get the size of bytes needed to store all bytes
int bytesize = count/ByteLength;
// Any bit left over another byte is necessary
if (count % ByteLength > 0)
{
bytesize++;
}
// For the result
byte[] bytes = new byte[bytesize];
// Must init to good value, all zero bit byte has value zero
// Lowest significant bit has a place value of 1, each position to
// to the left doubles the value
byte value = 0;
byte significance = 1;
int bytepos = 0;
int bitpos = startIndex;
while (bitpos - startIndex < count)
{
// If the bit is set add its value to the byte
if (array[bitpos])
value += significance;
bitpos++;
if (bitpos % ByteLength == 0)
{
// A full byte has been processed, store it
// increase output buffer index and reset work values
bytes[bytepos] = value;
bytepos++;
value = 0;
significance = 1;
}
else
{
// Another bit processed, next has doubled value
significance *= 2;
}
}
return bytes;
}
public static BitArray ShiftLeft(this BitArray array, int bitcount)
{
byte[] value = array.ToBytesArray();
byte[] temp = new byte[value.Length];
if (bitcount >= 8)
{
Array.Copy(value, bitcount/8, temp, 0, temp.Length - (bitcount/8));
}
else
{
Array.Copy(value, temp, temp.Length);
}
if (bitcount % 8 != 0)
{
for (int i = 0; i < temp.Length; i++)
{
temp[i] <<= bitcount % 8;
if (i < temp.Length - 1)
{
temp[i] |= (byte)(temp[i + 1] >> 8 - bitcount % 8);
}
}
}
return new BitArray(temp);
}
然而,字節的長度爲8,不能與我長太合身的結果是416或424(另一個字節)來代替。 421
最後,我嘗試了 「原始」 的方式:
for (int i = 0; i < bitcount; i++) { var lastValue = array[0]; for (var j = 0; j < array.Length - 1; j++) { array[j] = array[j + 1]; } array[array.Length - 1] = lastValue; }
我也檢查SO(例如, BitArray - Shift bits)但沒有爲我工作。
任何幫助將非常感激!
不能100%確定問題是什麼,以及這些鏈接沒有回答它。你想要一個數組,你可以左右移動(我假設在移位時加0)或者循環移位(所以如果右移,並且邊上有1,它會移動到開頭?) – Noctis 2014-08-31 22:34:36
您是否遇到算術(最左邊的位符號填充)和邏輯(最左邊位填零)位移之間的混淆?根據MSDN,左操作數(有符號或無符號整數類型)的性質決定了在C#規範下發生的操作。請注意,C++規範將處方視爲依賴於實現。 http://msdn.microsoft.com/en-us/library/xt18et0d.aspx – 2014-08-31 22:39:34
@Noctis - 我想要一個非循環操作。我將使用std :: bitset的C++實現轉換爲.NET。 我不認爲這是我的情況,因爲標準的基本類型,如int或單位,不能幫助我,因爲我需要自定義位數組長度。我的目標是使用BitArray將C++ std :: bitset運算符>>和<<轉換爲.NET。 – OzB 2014-08-31 22:53:28