Skip to content

Instantly share code, notes, and snippets.

@kofemann
Created October 9, 2014 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kofemann/fc3d1e937eca68df0293 to your computer and use it in GitHub Desktop.
Save kofemann/fc3d1e937eca68df0293 to your computer and use it in GitHub Desktop.
A vector of bits backended with a byte array.
import java.util.Arrays;
public class Bitmap {
private final byte[] _bitmap;
public Bitmap(int size) {
_bitmap = new byte[size];
}
public Bitmap(byte[] data) {
_bitmap = Arrays.copyOf(data, data.length);
}
public void set(int index) {
int chunk = index / 8;
int bit = index % 8;
_bitmap[chunk] |= 1 << bit;
}
public void clear(int index) {
int chunk = index / 8;
int bit = index % 8;
_bitmap[chunk] &= ~(1 << bit);
}
public boolean get(int index) {
int chunk = index / 8;
int bit = index % 8;
return (_bitmap[chunk] & 1 << bit) != 0;
}
public void flip(int index) {
int chunk = index / 8;
int bit = index % 8;
_bitmap[chunk] ^= (1 << bit);
}
public byte[] toByteArray() {
return Arrays.copyOf(_bitmap, _bitmap.length);
}
public String toString() {
return Arrays.toString(_bitmap);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment