Skip to content

Instantly share code, notes, and snippets.

@xstevens
Created September 5, 2012 18:18
Show Gist options
  • Save xstevens/3641802 to your computer and use it in GitHub Desktop.
Save xstevens/3641802 to your computer and use it in GitHub Desktop.
Half-baked BitSet using byte[] rather than long[]
package com.mozilla.telemetry;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* Half-baked bitset using ints rather than longs
*/
public class PseudoBitSet {
private byte[] bytes;
public PseudoBitSet(int numBits) {
bytes = new byte[(int)Math.ceil((double)numBits / 8.0d)];
System.out.println("words.length: " + bytes.length);
}
public void setBit(int bitIndex) {
System.out.println("Bit index: " + bitIndex);
if (bitIndex < 0) {
throw new IllegalArgumentException("Invalid bit index");
}
int byteIdx = (int)Math.floor((double)bitIndex / 8.0d);
if (byteIdx > bytes.length) {
throw new IllegalArgumentException("Bit index overflow");
}
System.out.println("Using byte index: " + byteIdx);
int bitIdx = bitIndex - (byteIdx * 8);
System.out.println("Using modified bit index: " + bitIdx);
bytes[byteIdx] |= (1 << bitIdx);
}
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 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) {
PseudoBitSet pbs = new PseudoBitSet(16);
pbs.setBit(0);
pbs.setBit(6);
pbs.setBit(11);
System.out.println("Little Endian Bit String Representation: " + pbs.toLittleEndianBinaryString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment