80 lines
2.2 KiB
Java
Raw Normal View History

2016-12-30 22:22:39 -08:00
// collectiontopics/Bits.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Demonstration of BitSet
2015-06-15 17:47:35 -07:00
import java.util.*;
public class Bits {
public static void printBitSet(BitSet b) {
2015-11-03 12:00:44 -08:00
System.out.println("bits: " + b);
2015-06-15 17:47:35 -07:00
StringBuilder bbits = new StringBuilder();
for(int j = 0; j < b.size() ; j++)
bbits.append(b.get(j) ? "1" : "0");
2015-11-03 12:00:44 -08:00
System.out.println("bit pattern: " + bbits);
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
2017-01-10 14:11:16 -08:00
Random rand = new Random(47);
2015-06-15 17:47:35 -07:00
// Take the LSB of nextInt():
byte bt = (byte)rand.nextInt();
BitSet bb = new BitSet();
for(int i = 7; i >= 0; i--)
if(((1 << i) & bt) != 0)
bb.set(i);
else
bb.clear(i);
2015-11-03 12:00:44 -08:00
System.out.println("byte value: " + bt);
2015-06-15 17:47:35 -07:00
printBitSet(bb);
short st = (short)rand.nextInt();
BitSet bs = new BitSet();
for(int i = 15; i >= 0; i--)
if(((1 << i) & st) != 0)
bs.set(i);
else
bs.clear(i);
2015-11-03 12:00:44 -08:00
System.out.println("short value: " + st);
2015-06-15 17:47:35 -07:00
printBitSet(bs);
int it = rand.nextInt();
BitSet bi = new BitSet();
for(int i = 31; i >= 0; i--)
if(((1 << i) & it) != 0)
bi.set(i);
else
bi.clear(i);
2015-11-03 12:00:44 -08:00
System.out.println("int value: " + it);
2015-06-15 17:47:35 -07:00
printBitSet(bi);
// Test bitsets >= 64 bits:
BitSet b127 = new BitSet();
b127.set(127);
2015-11-03 12:00:44 -08:00
System.out.println("set bit 127: " + b127);
2015-06-15 17:47:35 -07:00
BitSet b255 = new BitSet(65);
b255.set(255);
2015-11-03 12:00:44 -08:00
System.out.println("set bit 255: " + b255);
2015-06-15 17:47:35 -07:00
BitSet b1023 = new BitSet(512);
b1023.set(1023);
b1023.set(1024);
2015-11-03 12:00:44 -08:00
System.out.println("set bit 1023: " + b1023);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
byte value: -107
bits: {0, 2, 4, 7}
bit pattern: 101010010000000000000000000000000000000000
0000000000000000000000
short value: 1302
bits: {1, 2, 4, 8, 10}
bit pattern: 011010001010000000000000000000000000000000
0000000000000000000000
int value: -2014573909
bits: {0, 1, 3, 5, 7, 9, 11, 18, 19, 21, 22, 23, 24,
25, 26, 31}
bit pattern: 110101010101000000110111111000010000000000
0000000000000000000000
2015-06-15 17:47:35 -07:00
set bit 127: {127}
set bit 255: {255}
set bit 1023: {1023, 1024}
2015-09-07 11:44:36 -06:00
*/