Created
October 9, 2014 08:44
-
-
Save kofemann/fc3d1e937eca68df0293 to your computer and use it in GitHub Desktop.
A vector of bits backended with a byte array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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