下面列出了java.util.BitSet#toLongArray ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Rank9(BitSet set, long bitCount) {
long[] bits = set.toLongArray();
// One zero entry is needed at the end
bits = Arrays.copyOf(bits, 1 + (int) ((bitCount + 63) / 64));
this.bits = bits;
long length = bits.length * 64;
int numWords = (int) ((length + 63) / 64);
int numCounts = (int) ((length + 8 * 64 - 1) / (8 * 64)) * 2;
counts = new long[numCounts + 1];
long c = 0;
int pos = 0;
for (int i = 0; i < numWords; i += 8, pos += 2) {
counts[pos] = c;
c += Long.bitCount(bits[i]);
for (int j = 1; j < 8; j++) {
counts[pos + 1] |= (i + j <= numWords ? c - counts[pos] : 0x1ffL) << 9 * (j - 1);
if (i + j < numWords) {
c += Long.bitCount(bits[i + j]);
}
}
}
counts[numCounts] = c;
}
public NullComparator(BitSet mask, int count) {
super();
this.bigs = mask.toLongArray();
if(mask.cardinality() == 0){
mode = Mode.NONE;
four = 0;
eight = 0;
}else{
if(count > 64){
mode = Mode.BIG;
four = 0;
eight = 0;
}else if(count > 32){
mode = Mode.EIGHT;
four = 0;
eight = bigs[0];
} else {
mode = Mode.FOUR;
four = (int) bigs[0];
eight = 0;
}
}
}
public Rank9(BitSet set, long bitCount) {
long[] bits = set.toLongArray();
// One zero entry is needed at the end
bits = Arrays.copyOf(bits, 1 + (int) ((bitCount + 63) / 64));
this.bits = bits;
long length = bits.length * 64;
int numWords = (int) ((length + 63) / 64);
final int numCounts = (int) ((length + 8 * 64 - 1) / (8 * 64)) * 2;
counts = new long[numCounts + 1];
long c = 0;
int pos = 0;
for (int i = 0; i < numWords; i += 8, pos += 2) {
counts[pos] = c;
c += Long.bitCount(bits[i]);
for (int j = 1; j < 8; j++) {
counts[pos + 1] |= (i + j <= numWords ? c - counts[pos] : 0x1ffL) << 9 * (j - 1);
if (i + j < numWords) {
c += Long.bitCount(bits[i + j]);
}
}
}
counts[numCounts] = c;
}
@Override
public final Cidr4 recreateKey(final BitSet bits, final int numElements) {
if (bits.length() == 0) {
return new Cidr4(0, numElements);
}
// Maximum of 32 bits in a Cidr4 (IPv4 based)
int binary = (int) bits.toLongArray()[0];
// Shift our bits over if we are not 32 bits long
final int move = 32 - numElements;
if (move > 0) {
binary = binary << move;
}
return new Cidr4(binary, numElements);
}
public BitSet shiftRight(BitSet bits, int n) {
long[] words = bits.toLongArray();
// Expand array if there will be carry bits
if (words[words.length - 1] >>> n > 0) {
long[] tmp = new long[words.length + 1];
System.arraycopy(words, 0, tmp, 0, words.length);
words = tmp;
}
// Do the shift
for (int i = words.length - 1; i > 0; i--) {
words[i] <<= n; // Shift current word
words[i] |= words[i - 1] >>> (64 - n); // Do the carry
}
words[0] <<= n; // shift [0] separately, since no carry
return BitSet.valueOf(words);
}
public static void sched_setaffinity(final int pid, final BitSet affinity) {
final CLibrary lib = CLibrary.INSTANCE;
final cpu_set_t cpuset = new cpu_set_t();
final int size = version.isSameOrNewer(VERSION_2_6) ? cpu_set_t.SIZE_OF_CPU_SET_T : NativeLong.SIZE;
final long[] bits = affinity.toLongArray();
for (int i = 0; i < bits.length; i++) {
if (Platform.is64Bit()) {
cpuset.__bits[i].setValue(bits[i]);
} else {
cpuset.__bits[i * 2].setValue(bits[i] & 0xFFFFFFFFL);
cpuset.__bits[i * 2 + 1].setValue((bits[i] >>> 32) & 0xFFFFFFFFL);
}
}
try {
if (lib.sched_setaffinity(pid, size, cpuset) != 0) {
throw new IllegalStateException("sched_setaffinity(" + pid + ", " + size +
", 0x" + Utilities.toHexString(affinity) + ") failed; errno=" + Native.getLastError());
}
} catch (LastErrorException e) {
throw new IllegalStateException("sched_setaffinity(" + pid + ", " + size +
", 0x" + Utilities.toHexString(affinity) + ") failed; errno=" + e.getErrorCode(), e);
}
}
@Override
public String toString(BitSet value) {
StringBuilder builder = new StringBuilder();
for ( long token : value.toLongArray() ) {
if ( builder.length() > 0 ) {
builder.append( DELIMITER );
}
builder.append( Long.toString( token, 2 ) );
}
return builder.toString();
}
private int bitSetToInt(BitSet bitset){
int intValue = 0;
BitSet bitsetValue = bitset;
long[] data = bitsetValue.toLongArray();
if(data.length==1){
intValue = (int) data[0];
}
return intValue;
}
private static String print(BitSet bitSet) {
StringBuilder buf = new StringBuilder();
for (long lv: bitSet.toLongArray()) {
buf.insert(0, Long.toUnsignedString(lv, 2));
}
String b = buf.toString();
int count = bitSet.cardinality();
return "<html>0b" + ZERO_PAD.substring(b.length()) + b + "<br/> count: " + count;
}
public BitSet shiftLeft(BitSet bits, int n) {
final long[] words = bits.toLongArray();
// Do the shift
for (int i = 0; i < words.length - 1; i++) {
words[i] >>>= n; // Shift current word
words[i] |= words[i + 1] << (64 - n); // Do the carry
}
words[words.length - 1] >>>= n; // shift [words.length-1] separately, since no carry
return BitSet.valueOf(words);
}
@Test
public void testSortKeyTransform() {
final Random rand = new Random(SEED);
for (int i = 0; i < NUM_ITERATIONS; i++) {
// generate random long values representative of 64-bit sort keys
long val = rand.nextLong();
final BitSet set = BitSet.valueOf(new long[] {val});
// clear the first 12 bits of the random long because we truly only
// get 52-bits of precision (the mantissa) within the IEEE 754 spec
// which is what we have to work with for Redis Z-Scores
for (int a = 0; a < 12; a++) {
set.clear(a);
}
val = set.toLongArray()[0];
// now we have long randomly representing the 52-bits of precision
// we can work with within a z-score, let's cast to double and make
// sure we can go back and forth between z-score and sort key
final double originalScore = val;
final byte[] originalSortKey = RedisUtils.getSortKey(originalScore);
assertRepeatedTransform(originalScore, originalSortKey);
// now check that it still maintains consistency for lower length
// sort keys
for (int length = originalSortKey.length - 1; length >= 0; length--) {
final byte[] newOriginalSortKey = Arrays.copyOf(originalSortKey, length);
final double newOriginalScore = RedisUtils.getScore(newOriginalSortKey);
assertRepeatedTransform(newOriginalScore, newOriginalSortKey);
}
}
}
/**
* Constructor
*
* @param binary
* - binary value of this {@link VINT}, calculated from value if not specified
* @param length
* - length of this {@link VINT}
* @param value
* - value of this {@link VINT}
*/
public VINT(long binary, byte length, long value) {
if (binary == 0L) {
BitSet bs = BitSet.valueOf(new long[] { value });
bs.set(length * BIT_IN_BYTE - length);
this.binary = bs.toLongArray()[0];
} else {
this.binary = binary;
}
this.length = length;
this.value = value;
}
/**
* method to construct {@link VINT} based on its value
*
* @param value
* - value of {@link VINT}
* @return {@link VINT} corresponding to this value
*/
public static VINT fromValue(long value) {
BitSet bs = BitSet.valueOf(new long[] { value });
byte length = (byte) (1 + bs.length() / BIT_IN_BYTE);
if (bs.length() == length * BIT_IN_BYTE) {
length++;
}
bs.set(length * BIT_IN_BYTE - length);
long binary = bs.toLongArray()[0];
return new VINT(binary, length, value);
}
/**
* Creates a hexademical representation of the bit set
*
* @param set the bit set to convert
* @return the hexademical string representation
*/
public static String toHexString(final BitSet set) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(out);
final long[] longs = set.toLongArray();
for (long aLong : longs) {
writer.write(Long.toHexString(aLong));
}
writer.flush();
return new String(out.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
}
public static String toBinaryString(BitSet set) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(out);
final long[] longs = set.toLongArray();
for (long aLong : longs) {
writer.write(Long.toBinaryString(aLong));
}
writer.flush();
return new String(out.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
}
private byte[] sequenceCode(final double[] minValues, final int length) {
final double[] minsPerDimension = new double[dimensionCount];
Arrays.fill(minsPerDimension, 0.0);
final double[] maxesPerDimension = new double[dimensionCount];
Arrays.fill(maxesPerDimension, 1.0);
long cs = 0L;
for (int i = 0; i < length; i++) {
final double[] centers = new double[dimensionCount];
for (int j = 0; j < dimensionCount; j++) {
centers[j] = (minsPerDimension[j] + maxesPerDimension[j]) / 2.0;
}
final BitSet bits = new BitSet(dimensionCount);
for (int j = dimensionCount - 1; j >= 0; j--) {
if (minValues[j] >= centers[j]) {
bits.set(j);
}
}
long bTerm = 0L;
final long[] longs = bits.toLongArray();
if (longs.length > 0) {
bTerm = longs[0];
}
cs +=
1L
+ ((bTerm * (((long) (Math.pow(nthPowerOfTwo, g - i))) - 1L))
/ ((long) nthPowerOfTwo - 1));
for (int j = 0; j < dimensionCount; j++) {
if (minValues[j] < centers[j]) {
maxesPerDimension[j] = centers[j];
} else {
minsPerDimension[j] = centers[j];
}
}
}
return ByteArrayUtils.longToByteArray(cs);
}
public Set<Integer> getMatchingSlices(ByteString data, int start_slice, int end_slice)
{
long t1=System.nanoTime();
while(start_slice % 8 != 0) start_slice--;
while(end_slice % 8 != 0) end_slice++;
end_slice = Math.min(end_slice, slices);
Set<Integer> hashes = getHashIndexes(data);
BitSet matches = null;
Set<Integer> match_set = new HashSet<Integer>();
int count = end_slice - start_slice;
byte[] b = new byte[count / 8];
for(int x : hashes)
{
long pos = ((long)slices * (long)x + start_slice) / 8L;
long t1_read = System.nanoTime();
long_map.getBytes(pos, b);
TimeRecord.record(t1_read, "bloom_read");
long t1_bits = System.nanoTime();
BitSet bs = BitSet.valueOf(b);
if (matches == null)
{
matches = bs;
}
else
{
matches.and(bs);
}
TimeRecord.record(t1_bits, "bloom_bitkelp");
if (matches.isEmpty())
{
TimeRecord.record(t1,"bloom_getmatch_short");
return match_set;
}
}
long t1_list=System.nanoTime();
/*
* Reading one bit at a time is slow (it was actually taking measurable clock time on a pi 2).
* So splitting the bitset into longs and on a non-zero checking all those bits. Quite a bit faster.
*/
long[] vals = matches.toLongArray();
for(int idx = 0; idx<vals.length; idx++)
{
if (vals[idx] != 0)
{
int end = Math.min((idx+1) * 64, slices);
for(int i= idx * 64; i<end; i++)
{
if (matches.get(i)) match_set.add(i + start_slice);
}
}
}
/*for(int i=0; i<slices; i++)
{
if (matches.get(i)) match_set.add(i + start_slice);
}*/
TimeRecord.record(t1_list, "bloom_list");
TimeRecord.record(t1_list, "bloom_slices", slices);
TimeRecord.record(t1,"bloom_getmatch");
return match_set;
}