Używam java.util.BitSet
do przechowywania gęstego wektora bitów.Przesuwanie zestawu bitów Java
Chcę zaimplementować operację, która przesuwa bity o 1, analogicznie do >>>
na ints.
Czy istnieje funkcja biblioteki, która przesuwa BitSet
s?
Jeśli nie, czy jest lepszy sposób niż poniższy?
public static void logicalRightShift(BitSet bs) {
for (int i = 0; (i = bs.nextSetBit(i)) >= 0;) {
// i is the first bit in a run of set bits.
// Set any bit to the left of the run.
if (i != 0) { bs.set(i - 1); }
// Now i is the index of the bit after the end of the run.
i = bs.nextClearBit(i); // nextClearBit never returns -1.
// Clear the last bit of the run.
bs.clear(i - 1);
// 0000111100000...
// a b
// i starts off the loop at a, and ends the loop at b.
// The mutations change the run to
// 0001111000000...
}
}
Czekaj, to jest logiczne przesunięcie w lewo, a nie prawe przesunięcie logiczne. Dobrze? –
Myślę, że bit na indeks zero z BitSet jako lewy najbardziej. Nie ma wyraźnej najbardziej lub najmniej znaczącej bitowej drogi z ciągiem bitów, który reprezentuje liczbę całkowitą, więc oznaczanie kierunków jest dowolne. –