Skip to content

Instantly share code, notes, and snippets.

@deinspanjer
Forked from xstevens/gist:3641802
Created September 5, 2012 19:47
Show Gist options
  • Save deinspanjer/3643387 to your computer and use it in GitHub Desktop.
Save deinspanjer/3643387 to your computer and use it in GitHub Desktop.
Half-baked BitSet using byte[] rather than long[]
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class VerticaBinaryFormatBitSet {
private static final byte ZERO = (byte)0;
private byte[] bytes;
private boolean dirty = false;
private int numBits;
private int numBytes;
public VerticaBinaryFormatBitSet(int numBits) {
this.numBits = numBits;
this.numBytes = (int) Math.ceil((double) numBits / 8.0d);
bytes = new byte[this.numBytes];
}
public void setBit(int bitIndex) {
if (bitIndex < 0 || bitIndex >= numBits) {
throw new IllegalArgumentException("Invalid bit index");
}
int byteIdx = (int) Math.floor((double) bitIndex / 8.0d);
int bitIdx = bitIndex - (byteIdx * 8);
bytes[byteIdx] |= (1 << bitIdx);
dirty = true;
}
public boolean isDirty() {
return dirty;
}
public void clear() {
if (dirty) {
for (int i = 0; i < numBytes; i++) {
bytes[i] = ZERO;
}
dirty = false;
}
}
public byte[] toBytes() {
return bytes;
}
public byte[] toLittleEndianBytes() {
ByteBuffer buf = ByteBuffer.allocate(bytes.length);
buf.put(bytes);
return buf.order(ByteOrder.LITTLE_ENDIAN).array();
}
public int numBytes() {
return bytes.length;
}
public void writeBytes(ByteBuffer buf) {
buf.put(bytes);
}
public void writeBytes(int index, ByteBuffer buf) {
for (int i = index; i < (index + bytes.length); i++) {
buf.put(i, bytes[i]);
}
}
public String toLittleEndianBinaryString() {
StringBuilder sb = new StringBuilder();
for (byte b : this.toLittleEndianBytes()) {
sb.append(byteToLittleEndianBinaryString(b)).append(" ");
}
return sb.toString();
}
public static String byteToLittleEndianBinaryString(byte n) {
StringBuilder sb = new StringBuilder("00000000");
for (int bit = 7; bit >= 0; bit--) {
if (((n >> bit) & 1) > 0) {
sb.setCharAt(bit, '1');
}
}
return sb.toString();
}
public static void main(String[] args) {
try {
VerticaBinaryFormatBitSet vbs = new VerticaBinaryFormatBitSet(Integer.valueOf(args[0]));
for (int i = 1; i < args.length; i++) {
vbs.setBit(Integer.valueOf(args[i]));
}
System.out.println("Little Endian Bit String Representation: " + vbs.toLittleEndianBinaryString());
} catch (NumberFormatException e) {
System.err.println("Usage: VerticaBinaryFormatBitSet <num bits> [bit index to set]...");
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment