2012-06-16 52 views
0

我想將某些索引存儲在一系列位中。位數是
二的冪,假設最大索引爲255(起始索引爲0)是安全的。早些時候,我將整個索引存儲爲整數。但是這佔據了太多的記憶。有效存儲位索引

我想使用類似面具的東西。例如:如果我想存儲索引0,3,5,那麼我存儲101001,即41作爲一個整數。

問題是,我擁有的最大索引是255,並使用上述技術我可以存儲索引 ,直到64(使用64位整數)。有沒有其他方法可以做到這一點?

感謝:-)

+0

什麼語言正在使用? –

+0

我正在使用c# – Dynamite

+0

然後使用ulong數組。簡單。或BitArray,但有點慢。 – harold

回答

0

你可以用2個索引每一個位索引。 用10 Pratically位(索引1至10,設置位0,4,8):

單指數:

i = 0100010001 
Index1 = i 

兩個組合的索引:

i1 = 01000 
i2 = 10001 
Index2 = [i1, i2]; 
Index2.fragment_length = 5 

陣列 在僞碼,檢索或設置一點

set(Index, bit) { 
    fragment = quotient(bit, Index.flagment_length); //quotient = integer division 
    bit_index = module(bit, Index.flagment_length); //index of the bit in the fragment 
    set(Index[fragment], bit-or(Index[Fragment], bit-shift-left(1 << bit_index))); //Set the bit indexes vector fragment with or-ing the appropriate bitmask 
} 

get(Index, bit) { 
    fragment = quotient(bit, Index.flagment_length); //quotient = integer division 
    bit_index = module(bit, Index.flagment_length); //index of the bit in the fragment 
    if (get(Index[fragment], bit-and(Index[Fragment], bit-shift-left(1 << bit_index))) > 0) then true else false; //Get the bit indexes vector fragment bit with and-ing the appropriate bitmask and return true or false 
} 

我希望能夠了解滿足您的要求!

0

在Java中位索引製作容易,因爲下面的小教程...

這個類實現了一個按需增長的位向量。位集的每個組件都有一個布爾值。 BitSet的位由非負整數索引。各個索引位可以被檢查,設置或清除。一個BitSet可用於通過邏輯AND,邏輯或(OR)和邏輯異或操作來修改另一個BitSet的內容。

默認情況下,該集合中的所有位最初都具有值false。

每一個比特組都有一個當前大小,這個比特組是目前正在使用的比特數。請注意,大小與位集的實現有關,所以它可能隨實現而改變。位集的長度與位集的邏輯長度有關,並且與實現無關地定義。

除非另有說明,否則將null參數傳遞給BitSet中的任何方法將導致NullPointerException。 BitSet對於多線程應用並不安全,無需外部同步。

1

.NET擁有一個內置的類這樣的事情:BitArray

這將讓你存儲的比特串(在布爾變量的形式)有效。

你可以用AndOrXorNot方法上BitArray s以後進行按位運算。

您可以用bools,字節或整數初始化一個BitArray。例如,你可以用00101100來初始化它:

BitArray bits = new BitArray(new byte[] { 0x2C }); // 0x2C == 00101100