集册 Java实例教程 在位向量上执行按位运算

在位向量上执行按位运算

欢马劈雪     最近更新时间:2020-01-02 10:19:05

450
在位向量上执行按位运算

import java.util.BitSet;/** 来自 n o w j a v a . c o m**/


public class Main {

  public static void main(String[] argv) {

    // Create the bitset

    BitSet bits = new BitSet();


    // Set a bit on

    bits.set(2); // 100 = decimal 4


    // Retrieving the value of a bit

    boolean b = bits.get(0); // false

    b = bits.get(2); // true


    // Clear a bit

    bits.clear(1);


    // Setting a range of bits//from N o  w  J a v a . c o m - 时  代  Java

    BitSet bits2 = new BitSet();

    bits2.set(1, 4); // 1110


    // And'ing two bitsets

    bits.and(bits2); // 0100


    // Xor'ing two bitsets

    bits.xor(bits2); // 1010


    // Flip all bits in the bitset

    bits.flip(0, bits.length()); 
展开阅读全文