Java Code Examples for java.util.BitSet#valueOf()

The following examples show how to use java.util.BitSet#valueOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BitSetStreamTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRandomStream() {
    final int size = 1024 * 1024;
    final int[] seeds = {
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
            43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
    final byte[] bytes = new byte[size];
    for (int seed : seeds) {
        final Random random = new Random(seed);
        random.nextBytes(bytes);
        final BitSet bitSet = BitSet.valueOf(bytes);
        final int cardinality = bitSet.cardinality();
        final IntStream stream = bitSet.stream();
        final int[] array = stream.toArray();
        assertEquals(array.length, cardinality);
        int nextSetBit = -1;
        for (int i=0; i < cardinality; i++) {
            nextSetBit = bitSet.nextSetBit(nextSetBit + 1);
            assertEquals(array[i], nextSetBit);
        }
    }
}
 
Example 2
Source File: GenericCharacteristicParser.java    From bluetooth-gatt-parser with Apache License 2.0 6 votes vote down vote up
private BitSet serialize(FieldHolder holder) {
    FieldFormat fieldFormat = holder.getField().getFormat();
    switch (fieldFormat.getType()) {
        case BOOLEAN: return serialize(holder.getBoolean(null));
        case UINT:
        case SINT: return serializeReal(holder);
        case FLOAT_IEE754: return serializeFloat(
                BluetoothGattParserFactory.getIEEE754FloatingPointNumberFormatter(), holder);
        case FLOAT_IEE11073: return serializeFloat(
                BluetoothGattParserFactory.getIEEE11073FloatingPointNumberFormatter(), holder);
        case UTF8S: return serializeString(holder, "UTF-8");
        case UTF16S: return serializeString(holder, "UTF-16");
        case STRUCT: return BitSet.valueOf((byte[]) holder.getRawValue());
        default:
            throw new IllegalStateException("Unsupported field format: " + fieldFormat.getType());
    }
}
 
Example 3
Source File: IEEE754FloatingPointNumberFormatterTest.java    From bluetooth-gatt-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeSerializeDouble() throws Exception {
    BitSet bitSet = BitSet.valueOf(new long[]{Double.doubleToLongBits(1F)});
    Double deserialized = formatter.deserializeDouble(bitSet);
    assertEquals(1F, deserialized, 0.0);
    assertEquals(bitSet, formatter.serializeDouble(deserialized));

    bitSet = BitSet.valueOf(new long[]{1});
    deserialized = formatter.deserializeDouble(bitSet);
    assertEquals(Double.MIN_VALUE, deserialized, 0.0);
    assertEquals(bitSet, formatter.serializeDouble(deserialized));

    bitSet = BitSet.valueOf(new long[]{Double.doubleToLongBits(Double.MAX_VALUE)});
    deserialized = formatter.deserializeDouble(bitSet);
    assertEquals(Double.MAX_VALUE, deserialized, 0.0);
    assertEquals(bitSet, formatter.serializeDouble(deserialized));
}
 
Example 4
Source File: BitSetStreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRandomStream() {
    final int size = 1024 * 1024;
    final int[] seeds = {
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
            43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
    final byte[] bytes = new byte[size];
    for (int seed : seeds) {
        final Random random = new Random(seed);
        random.nextBytes(bytes);

        BitSet bitSet = BitSet.valueOf(bytes);
        testBitSetContents(bitSet, bitSet.stream().toArray());
        testBitSetContents(bitSet, bitSet.stream().parallel().toArray());
    }
}
 
Example 5
Source File: VINT.java    From red5-io with Apache License 2.0 6 votes vote down vote up
/**
 * method to construct {@link VINT} based on its binary representation
 * 
 * @param binary
 *            - binary value of {@link VINT}
 * @return {@link VINT} corresponding to this binary
 */
public static VINT fromBinary(long binary) {
    BitSet bs = BitSet.valueOf(new long[] { binary });
    long mask = MASK_BYTE_1;
    byte length = 1;
    if (bs.length() > 3 * BIT_IN_BYTE) {
        mask = MASK_BYTE_4;
        length = 4;
    } else if (bs.length() > 2 * BIT_IN_BYTE) {
        mask = MASK_BYTE_3;
        length = 3;
    } else if (bs.length() > 1 * BIT_IN_BYTE) {
        mask = MASK_BYTE_2;
        length = 2;
    }
    long value = binary & mask;
    return new VINT(binary, length, value);
}
 
Example 6
Source File: BitSetTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static void assertBitSet(long[] longs, String s) {
    // Test BitSet.valueOf(long[]).
    assertBitSet(BitSet.valueOf(longs), longs, s);
    // Test BitSet.valueOf(LongBuffer).
    assertBitSet(BitSet.valueOf(LongBuffer.wrap(longs)), longs, s);
    // Surround 'longs' with junk set bits but exclude them from the LongBuffer.
    long[] paddedLongs = new long[1 + longs.length + 1];
    paddedLongs[0] = paddedLongs[paddedLongs.length - 1] = -1L;
    System.arraycopy(longs, 0, paddedLongs, 1, longs.length);
    assertBitSet(BitSet.valueOf(LongBuffer.wrap(paddedLongs, 1, longs.length)), longs, s);

    // Check that the long[] is copied.
    if (longs.length > 0) {
        BitSet original = BitSet.valueOf(longs);
        longs[0] = ~longs[0];
        assertFalse(BitSet.valueOf(longs).equals(original));
    }
}
 
Example 7
Source File: OmOzoneAclMap.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public boolean hasAccess(OzoneAclInfo acl) {
  if (acl == null) {
    return false;
  }

  BitSet aclBitSet = getAcl(acl.getType(), acl.getName());
  if (aclBitSet == null) {
    return false;
  }
  BitSet result = BitSet.valueOf(acl.getRights().toByteArray());
  result.and(aclBitSet);
  return (!result.equals(ZERO_BITSET) || aclBitSet.get(ALL.ordinal()))
      && !aclBitSet.get(NONE.ordinal());
}
 
Example 8
Source File: TestBloomFilters.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testNot() {
  BloomFilter bf = new BloomFilter(8, 1, Hash.JENKINS_HASH);
  bf.bits = BitSet.valueOf(new byte[] { (byte) 0x95 });
  BitSet origBitSet = (BitSet) bf.bits.clone();
  bf.not();
  assertFalse("BloomFilter#not should have inverted all bits",
              bf.bits.intersects(origBitSet));
}
 
Example 9
Source File: ItemPairsSamplingUDTF.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
private void sampleWithoutReplacement(int numPosItems, int numNegItems,
        @Nonnull final BitSet bitset) throws HiveException {
    final BitSet bitsetForPosSampling = bitset;
    final BitSet bitsetForNegSampling = BitSet.valueOf(bitset.toLongArray());

    final int numSamples = Math.max(1, Math.round(numPosItems * samplingRate));
    for (int s = 0; s < numSamples; s++) {
        int nth = _rand.nextInt(numPosItems);
        int i = BitUtils.indexOfSetBit(bitsetForPosSampling, nth);
        if (i == -1) {
            throw new UDFArgumentException(
                "Cannot find a value for " + nth + "-th element in bitset " + bitset.toString()
                        + " where numPosItems = " + numPosItems);
        }
        bitsetForPosSampling.set(i, false);
        --numPosItems;

        nth = _rand.nextInt(numNegItems);
        int j = BitUtils.indexOfClearBit(bitsetForNegSampling, nth, maxItemId);
        if (j < 0 || j > maxItemId) {
            throw new UDFArgumentException("j MUST be in [0," + maxItemId + "] but j was " + j);
        }
        bitsetForNegSampling.set(j, true);
        --numNegItems;

        posItemId.set(i);
        negItemId.set(j);
        forward(forwardObjs);

        if (numPosItems <= 0) {
            // cannot draw a positive example anymore
            return;
        } else if (numNegItems <= 0) {
            // cannot draw a negative example anymore
            return;
        }
    }
}
 
Example 10
Source File: SomeOperate.java    From Redis_Learning with Apache License 2.0 5 votes vote down vote up
public static int allUniqueCount(Jedis jedis, String action, String... dates) {
	BitSet all = new BitSet();
	for (String date : dates) {
		String key = action + ":" + date;
		BitSet user = BitSet.valueOf(jedis.get(key.getBytes()));
		all.or(user);
	}
	return all.cardinality();// ���ظ��ַ�������Ϊ1�ĸ���
}
 
Example 11
Source File: AddressSpecs.java    From aion with MIT License 5 votes vote down vote up
public static Optional<String> checksummedAddress(String address) {
    if (address == null) return Optional.empty();
    address = address.replaceFirst("^0x", "");
    if (address.length() != 64) return Optional.empty();

    byte[] h;
    try {
        h = HashUtil.h256(ByteUtil.hexStringToBytes(address));
    } catch (Exception e) {
        e.printStackTrace();
        return Optional.empty();
    }
    if (h == null) return Optional.empty(); // address is invalid
    BitSet b = BitSet.valueOf(h);
    char[] caddr = address.toCharArray();
    for (int i = 0; i < 64; i++) {
        if (Character.isDigit(caddr[i])) continue;

        if (Character.isAlphabetic(caddr[i])) {
            caddr[i] =
                    b.get(i)
                            ? Character.toUpperCase(caddr[i])
                            : Character.toLowerCase(caddr[i]);
        }
    }
    return Optional.of(String.valueOf(caddr));
}
 
Example 12
Source File: RegularDataDecoder.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
private void readBitmap(ByteBuffer buffer) {
  int length = ReadWriteIOUtils.readInt(buffer);
  byte[] byteArr = new byte[length];
  buffer.get(byteArr);
  bitmap = BitSet.valueOf(byteArr);
  bitmapIndex = 0;
}
 
Example 13
Source File: SomeOperate.java    From Redis_Learning with Apache License 2.0 4 votes vote down vote up
public static int uniqueCount(Jedis jedis, String action, String date) {
	String key = action + ":" + date;
	System.out.println(key + " "+key.getBytes() + " " +jedis.get(key.getBytes()));
	BitSet user = BitSet.valueOf(jedis.get(key.getBytes()));
	return user.cardinality();// ���ظ��ַ�������Ϊ1�ĸ���
}
 
Example 14
Source File: BloomFilterMurmur3.java    From FxDock with Apache License 2.0 4 votes vote down vote up
public BloomFilterMurmur3(int hashFunctionCount, byte[] b)
{
	this.hashFunctionCount = hashFunctionCount;
	this.bitSetSize = b.length * 8;
	bits = BitSet.valueOf(b);
}
 
Example 15
Source File: BitSetBasedSimpleGraphGenerator.java    From JQF with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void generateGraph(Graph<V, E> graph, VertexFactory<V> vertexFactory, Map<String, V> map) {
    // Calculate number of edges to generate
    boolean isDirected = graph instanceof DirectedGraph;
    int numEdges = numEdges(isDirected);

    // Figure out how many random bytes to generate for this purpose
    int numBytes = (numEdges + 7) / 8;  // Equal to ceil(numEdges/8.0)
    byte[] bytes = new byte[numBytes];

    // Generate random bytes
    rng.nextBytes(bytes);

    // Convert to bitset
    BitSet bitSet = BitSet.valueOf(bytes);

    // Generate nodes
    V[] vertices = (V[]) new Object[n];
    for(int i = 0; i < n; ++i) {
        V v = vertexFactory.createVertex();
        graph.addVertex(v);
        vertices[i] = v;
    }

    // Add edges as necessary
    int k = 0;
    for (int i = 0; i < n; i++) {
        V s = vertices[i];
        for (int j = 0; j < i; j++) {
            V t = vertices[j];
            // Get next boolean to decide s --> t
            if (bitSet.get(k++)) {
                graph.addEdge(s, t);
            }

            if (isDirected) {
                // Get next boolean to decide t --> t
                if (bitSet.get(k++)) {
                    graph.addEdge(t, s);
                }
            }
        }
    }
    // Sanity check
    assert(k == numEdges);




}
 
Example 16
Source File: TwosComplementNumberFormatterTest.java    From bluetooth-gatt-parser with Apache License 2.0 4 votes vote down vote up
private BitSet getBytes(int byte1, int byte2) {
    return BitSet.valueOf(new byte[] {(byte) byte2, (byte) byte1});
}
 
Example 17
Source File: BooleanSettingMapFactory.java    From helper with MIT License 3 votes vote down vote up
/**
 * Decodes the given byte array to a {@link BooleanSettingMap}.
 *
 * <p>Operates on the reverse of {@link BooleanSettingMap#encode()}.</p>
 *
 * @param buf the byte array
 * @return the decoded map
 */
public BooleanSettingMap<S> decode(byte[] buf) {
    BitSet bits = BitSet.valueOf(buf);
    if (bits.length() > this.settings.length) {
        bits.clear(this.settings.length, bits.length());
    }
    return new BooleanSettingMap<>(this, bits);
}
 
Example 18
Source File: KeyBitSet.java    From exonum-java-binding with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new bit set.
 *
 * @param key key bytes
 * @param length a length in bits, i.e., the number of significant bits in key array
 */
public KeyBitSet(byte[] key, int length) {
  checkArgument(length >= 0, "length (%s) must be non-negative", length);
  keyBits = BitSet.valueOf(key);
  this.length = length;
}
 
Example 19
Source File: PrefixSpace.java    From batfish with Apache License 2.0 2 votes vote down vote up
/**
 * Converts an IPv4 address into a {@link BitSet} useful for prefix matching. The highest bit of
 * the address is the lowest bit of the bitset: the address 128.0.0.0 when converted to a {@link
 * BitSet} has only the lowest bit set.
 */
// visible for testing
static BitSet getAddressBits(Ip address) {
  return BitSet.valueOf(new long[] {Integer.reverse((int) address.asLong()) & 0xffffffffL});
}
 
Example 20
Source File: SerializableObject.java    From lucene-solr with Apache License 2.0 2 votes vote down vote up
/** Read a bitset from a stream.
 * @param inputStream is the input stream.
 * @return the bitset read from the stream.
 */
static BitSet readBitSet(final InputStream inputStream) throws IOException {
  return BitSet.valueOf(readByteArray(inputStream));
}