Skip to content

Instantly share code, notes, and snippets.

@gmuller
Created May 20, 2012 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gmuller/2758696 to your computer and use it in GitHub Desktop.
Save gmuller/2758696 to your computer and use it in GitHub Desktop.
An attempt to understand byte and bit ordering in redis bitsets
import java.util.BitSet;
import redis.clients.jedis.Jedis;
public class SieveOfEratosthenes {
/**
* @param args
*/
public static void main(final String[] args) {
// setup values
final Jedis redis = new Jedis("localhost");
final String sieveSetBit = "sieveSetBit";
final String sieveSetKey = "sieveSetKey";
final int length = 20;
final BitSet sieve = new BitSet(length);
sieve.flip(2, length);
// create bitset of all values
for (int i = 0; i < length; i++) {
if (sieve.get(i)) {
for (int j = i * 2; j < length; j += i) {
sieve.set(j, false);
}
}
}
// Write 2 bitsets to redis
// 1. setbit through redis
for (int i = 0; i < sieve.length(); i++) {
if (sieve.get(i)) {
redis.setbit(sieveSetBit, i, true);
}
}
// 2. Set entire bitset
redis.set(sieveSetKey.getBytes(), sieve.toByteArray());
// Compare bitsets from Redis when retrieved via getKey
final String sieveBitString = redis.get(sieveSetBit);
final String sieveKeyString = redis.get(sieveSetKey);
final BitSet setBitSieve = BitSet.valueOf(sieveBitString.getBytes());
final BitSet setKeySieve = BitSet.valueOf(sieveKeyString.getBytes());
final BitSet reverseSetBit = fromByteArray(sieveBitString.getBytes());
final BitSet reverseSetKey = fromByteArray(sieveKeyString.getBytes());
System.out.println(setBitSieve);
System.out.println(setKeySieve);
System.out.println(reverseSetBit);
System.out.println(reverseSetKey);
}
public static BitSet fromByteArray(final byte[] bytes) {
final BitSet bits = new BitSet();
for (int i = 0; i < bytes.length * 8; i++) {
if ((bytes[bytes.length - i / 8 - 1] & (1 << (i % 8))) > 0) {
bits.set(i);
}
}
return bits;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment